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
 Every Group in a Column

Author  Topic 

Adel99
Starting Member

7 Posts

Posted - 2011-11-15 : 23:48:24
I have two tables: Students and Voilations. The Students table's PK is StudentId. The Voilations table contains voliations a student has, which can be of three types ('Absence', 'Late', 'Escape'). The type of voilation is stored as nvarchar in the VoilationType column. So, the Voilations tables is like:
VoilationId | StudentId | VoilationType | VoilationDateTime | Comments

I want to get the number of every type of voilation every student has. So, I used:
GROUP BY StudentId, VoilationType
But this gave me something like this:
----------------------------------
StudentId | VoilationType | exper1
----------------------------------
103 | Absence | 2
102 | Absence | 1
103 | Late | 1
103 | Escape | 5
102 | Late | 2
----------------------------------

But I want every type of voilation to be in a different column. Like this:
--------------------------------------------------
StudentId | AbsenceCases | LateCases | EscapeCases
--------------------------------------------------
103 | 2 | 1 | 5
102 | 1 | 2 | 0 <-- or NULL
--------------------------------------------------

How to do that? Thank you.

Adel,

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-16 : 00:46:46
[code]
SELECT s.StudentId,
SUM(CASE WHEN v.VoilationType ='Absence' THEN 1 ELSE 0 END) AS [AbsenceCases],
SUM(CASE WHEN v.VoilationType ='Late' THEN 1 ELSE 0 END) AS [LateCases],
SUM(CASE WHEN v.VoilationType ='Escape' THEN 1 ELSE 0 END) AS [EscapeCases]
FROM Students s
INNER JOIN Voilations v
ON v.StudentId = s.StudentId
GROUP BY s.StudentId
[/code]

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

Go to Top of Page

Adel99
Starting Member

7 Posts

Posted - 2011-11-16 : 01:39:03
Thank you so much. It worked perfectly. Thank you, visakh16.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-16 : 01:44:37
wc

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

Go to Top of Page
   

- Advertisement -