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
 Multiple Selects on Table

Author  Topic 

FernandoLorival
Starting Member

19 Posts

Posted - 2008-04-14 : 12:07:31
Hi All,
I have a table that looks like this:

Date | Event
01/01/2008 | CRG
01/01/2008 | MAG
01/01/2008 | CPY
01/02/2008 | CPY
01/02/2008 | MAG
01/02/2008 | MAG
01/03/2008 | CRG
01/03/2008 | CPY

I need to display the data like this:

Date | CRG | MAG | CPY | Total
01/01/2008 | 1 | 1 | 1 | 3
01/02/2008 | 0 | 2 | 2 | 4
01/03/2008 | 1 | 0 | 1 | 2

Thank you so much for your help.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-04-14 : 12:10:48
[code]SELECT Date,
COUNT(CASE WHEN Event='CRG' THEN Event ELSE NULL END) AS CRG,
COUNT(CASE WHEN Event='MAG' THEN Event ELSE NULL END) AS MAG,
COUNT(CASE WHEN Event='CPY' THEN Event ELSE NULL END) AS CPY,
COUNT(Event) AS Total
FROM YourTable
GROUP BY Date[/code]
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2008-04-14 : 12:33:09
visakh answer is correct with a slight modification in the display of date

SELECT CONVERT(VARCHAR(50),Date,1O1) AS DATE,
COUNT(CASE WHEN Event='CRG' THEN Event ELSE NULL END) AS CRG,
COUNT(CASE WHEN Event='MAG' THEN Event ELSE NULL END) AS MAG,
COUNT(CASE WHEN Event='CPY' THEN Event ELSE NULL END) AS CPY,
COUNT(Event) AS Total
FROM YourTable
GROUP BY Date
Go to Top of Page

FernandoLorival
Starting Member

19 Posts

Posted - 2008-04-14 : 13:18:45
Excellent!!!
Thank you so much for your quick response!

Cheers
Go to Top of Page
   

- Advertisement -