question

Rob Allen avatar image
Rob Allen asked

How should I organize a query of counts matching different criteria

I am trying to write a query which produces a summary or statuses but my current attempt is ugly and takes too long (over a minute).

Given this sample data:

Name       ID      Status                    
---------------------------                    
 A         1         6                      
 A         2         6                    
 A         3         2                    
 B         4         2                    
 B         5         1                    
 C         6         1                    
 D         7         4                    
 D         8         6                    
 A         9         6                    
 B        10         1                    
 A        11         1                    

I want to produce this summary data:

Name     1    2    3   4   5   6                    
---------------------------------                    
 A       1    1    0   0   0   3                    
 B       2    1    0   0   0   0                    
 C       0    0    0   0   0   1                    
 D       0    0    0   1   0   6                    

How can I write this query so that it can stay fast and flexible?

sql-server-2005t-sqlselectpivotaggregates
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

· Write an Answer
TG avatar image
TG answered

Assuming your status values don't change you can use PIVOT:

select p.Name,[1],[2],[3],[4],[5],[6]            
from YourTable            
pivot (count(id) for status in ([1],[2],[3],[4],[5],[6]) ) p            
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.