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
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Using count twice in one query?

Author  Topic 

ashburnham
Starting Member

2 Posts

Posted - 2008-07-16 : 08:14:04
I have a simple database where I've got 2 columns "product" and "flag" where I want to count occurrences. "product" contains random product names and "flag" will have an "x" if flagged or anything except and "x" if not flagged.

I currently use two queries as follows:

SELECT product, COUNT(product) AS flags FROM `TABLE` WHERE flag = 'x' GROUP BY product ORDER BY flags DESC

which gives a table:

| product | flags |
-------------------
| pear | 6 |
| apple | 4 |
| orange | 1 |
-------------------

SELECT product, COUNT(product) AS noflags FROM `TABLE` WHERE flag != 'x' GROUP BY product ORDER BY noflags DESC

which gives a table:

| product | noflags |
---------------------
| apple | 4 |
| pear | 3 |
| orange | 0 |
---------------------

I want to combine these two queries so I am effectively counting occurrences twice to produce a table as follows:

| product | flags | no flags |
------------------------------
| pear | 6 | 3 |
| apple | 4 | 4 |
| orange | 1 | 0 |
------------------------------

Any help much appreciated.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-07-16 : 08:18:33
SELECT Product,
SUM(CASE WHEN Flag = 'x' THEN 1 ELSE 0 END) AS Flags,
SUM(CASE WHEN Flag = 'x' THEN 0 ELSE 1 END) AS NoFlags
FROM Table
GROUP BY Product


E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

ashburnham
Starting Member

2 Posts

Posted - 2008-07-16 : 09:44:26
works a treat - thanks
Go to Top of Page
   

- Advertisement -