Tuesday, December 2, 2008

SQL SERVER SQL Query Conditional Count with CASE Clause inside COUNT

Suppose you have a master and child table in the following structure and you want to find out how many thing of each category is sold or not

Category       
Music       
Book       
Movie       


Category    Name    Sold
Music    Love Song    T
Music    Rock    T
Music    Classical    F
Book    Dictionary    T
Book    Fiction    T
Book    Textbook    F
Movie    James Bond    F
Movie    MI3    F


You will write the following query for it

Select
    Category
    ,Count(Name) as ProductCount
    ,Count(Case When Sold = 'T' Then Name Else NULL End) as SoldCount
    ,Count(Case When Sold = 'F' Then Name Else NULL End) as UnsoldCount
From Product
Group By Category

NOTE: the NULL value in the else clause is critical, if you put zero there, the query will not work.

No comments: