Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 QuerySame Table Field for Different Results

Author  Topic 

mattie
Starting Member

13 Posts

Posted - 2012-10-08 : 13:33:37
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
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-10-08 : 14:34:54
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

52326 Posts

Posted - 2012-10-08 : 19:52:26
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
   

- Advertisement -