SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 QuerySame Table Field for Different Results
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

mattie
Starting Member

13 Posts

Posted - 10/08/2012 :  13:33:37  Show Profile  Reply with Quote
What is the best way to query the same table, moreover the same field for different results?
E.g.
1st Statement
Select Tickets, count (*) as Total_Tickets
From Orders

2nd statement
Select Tickets, count (*) as Mail_Order
From Orders
Where Tickets Like Any (a%, b%, c%)

3rd Statement
Select Tickets, count (*) as Web_order
From Orders
Where Tickets Not Like All (a%,b%,c%)

--And Produce a result :
Total_Tickets
Mail_order/Total_Tickets as Mail_Percentage
Web_Order/Total_tickets as Web_Percentage

sunitabeck
Flowing Fount of Yak Knowledge

5155 Posts

Posted - 10/08/2012 :  14:34:54  Show Profile  Reply with Quote
I don't think SQL Server allows the use of ANY/ALL/SOME keywords in the context you are using. You can write the query like this:
SELECT
	Tickets,
	COUNT(*) AS Total_Tickets,
	SUM(CASE WHEN Tickets LIKE 'a%' OR Tickets LIKE 'b%' 
		OR Tickers LIKE 'c%' THEN 1 ELSE 0 END) AS Mail_Order,
	SUM(CASE WHEN Tickers NOT LIKE 'a%' AND Tickets NOT LIKE 'b%' 
		AND Tickers NOT LIKE 'c%' THEN 1 ELSE 0 END) AS Web_order
FROM
	tbl
GROUP BY
	Tickers
You can of course, divide appropriately to get the percentages etc.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 10/08/2012 :  19:52:26  Show Profile  Reply with Quote
for percentages make sure you modify them as

SUM(CASE WHEN Tickets LIKE 'a%' OR Tickets LIKE 'b%'
OR Tickers LIKE 'c%' THEN 1.0 ELSE 0.0 END)/COUNT(*)
etc

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000