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 2005 Forums
 Transact-SQL (2005)
 counting records ased on ids in table

Author  Topic 

cwfontan
Yak Posting Veteran

87 Posts

Posted - 2009-08-24 : 16:37:54
Need to count how many times a customer has been to each state
table
Cust# | DeliverToState | LoadUnloadState
------------------------------------------
101 | MI | OH
101 | MI | MI
102 | IN | MI

Results

Cust# | qty2MI | qty2OH | qty2IN
101 | 3 | 1 | 0
102 | 1 | 0 | 1

cat_jesus
Aged Yak Warrior

547 Posts

Posted - 2009-08-24 : 16:52:08
Define "been to" please.

An infinite universe is the ultimate cartesian product.
Go to Top of Page

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2009-08-24 : 16:54:57
Here's one way:

declare @table table (Cust# int, DeliverToState char(2), LoadUnloadState char(2))
insert @table
select 101, 'MI', 'OH' union all
select 101, 'MI', 'MI' union all
select 102, 'IN', 'MI'

select p.cust#
,[mi] as Qty2MI
,[OH] as Qty2OH
,[IN] as Qty2IN
from (
select up.cust#, up.val as st
from @table
unpivot (val for cols in (DeliverToState, LoadUnloadState)) up
) p
pivot (count(st) for st in ([MI],[OH],[IN])) p


OUTPUT:

cust# Qty2MI Qty2OH Qty2IN
----------- ----------- ----------- -----------
101 3 1 0
102 1 0 1


Be One with the Optimizer
TG
Go to Top of Page

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-08-25 : 02:08:43
try like this too


SELECT cust#,COUNT(CASE WHEN val = 'MI' THEN val END) AS Qty2MI,
COUNT(CASE WHEN val = 'OH' THEN val END) AS Qty2OH,
COUNT(CASE WHEN val = 'IN' THEN val END) AS Qty2IN
FROM (
SELECT cust#,delivertostate AS val FROM @table
UNION ALL
SELECT cust#,LoadUnloadState FROM @table
)s
GROUP BY cust#
Go to Top of Page
   

- Advertisement -