x

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?

more ▼

asked Feb 12, 2010 at 03:57 PM in Default

Rob Allen gravatar image

Rob Allen
34 4 4 5

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

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
more ▼

answered Feb 12, 2010 at 05:12 PM

TG gravatar image

TG
1.8k 1 3

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x1951
x991
x110
x82
x61

asked: Feb 12, 2010 at 03:57 PM

Seen: 1185 times

Last Updated: Feb 14, 2010 at 12:02 PM