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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 help with crosstab in northwind

Author  Topic 

ashley.sql
Constraint Violating Yak Guru

299 Posts

Posted - 2007-11-27 : 17:55:43
i have a query in north wind db

select

sum(case when freight < 10 then 1 else 0 end) CAT1,
sum(case when freight >10 and freight < 20 then 1 else 0 end) CAT2,
sum(case when freight >20 and freight < 30 then 1 else 0 end) CAT3,
sum(case when freight >30 and freight < 40 then 1 else 0 end) CAT4,
sum(case when freight >40 then 1 else 0 end) CAT5
from orders


this given me result like

CAT1 CAT2 CAT3 CAT4 CAT5
----------- ----------- ----------- ----------- -----------
176 91 80 64 419



but I want the result to be like

CATEGORY COUNT
CAT1 176
CAT2 91
CAT3 80
CAT4 64
CAT5 419

IS THERE A SIMPLE WAY TO DO THIS CROSSTAB.


-----------------------------------------------------------------------------------------------
Ashley Rhodes

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2007-11-27 : 18:50:18
Here is one way:

select category
,count(*) [count]
from (
select case
when freight < 10 then 'CAT1'
when freight >10 and freight < 20 then 'CAT2'
when freight >20 and freight < 30 then 'CAT3'
when freight >30 and freight < 40 then 'CAT4'
when freight >40 then 'CAT5'
end as category
from orders
) a
group by category
order by category

output:
category count
-------- -----------
CAT1 176
CAT2 91
CAT3 80
CAT4 64
CAT5 419


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -