Reputation: 4063
I've been trying to create a pivot for following query :
select mainstate, customertypeid, count(1) as [counter] from customers group by customertypeid, mainstate
This query should display as many customers types per state, it looks like this (order by doesn't matter) :
State|customertypeid|counter
UT 3 200
CA 3 500
NY 3 300
UT 2 100
CA 2 200
NY 2 120
UT 1 20
CA 1 50
NY 1 30
I've tried to use PIVOT as follow (I'm sure I'm wrong) :
SELECT *
FROM ( select mainstate, customertypeid, count(1) as [counter] from customers where customertypeid in (1,2,3) and mainstate != '' group by customertypeid, mainstate) as NonPivotedDataForReport2
PIVOT
(
COUNT([counter])
FOR mainstate IN ([# of Amb],[# Whole Sale Customers],[# Retail Customers])
) AS PivotedDataForReport2
I'm getting this :
customertypeid|type1|type2|type3
1 0 0 0
2 0 0 0
3 0 0 0
and the report should look like this :
State|type1|type2|type3
UT 20 100 200
CA 50 200 500
NY 30 120 300
*Ps : I don't really want to go back to CASE + SUM Statement,
Thanks a lot!
Upvotes: 0
Views: 283
Reputation: 482
This (perhaps slightly edited) should do the job for you without case/sum/pivot. Create a temp table, insert starting data and then dynamically add columns depending on how many customer type ids there is.
declare @s varchar(10), @xx1 varchar(500)
select distinct state into #temp from customers
DECLARE myCursor CURSOR FOR SELECT distinct customertypeid from customers
open MyCursor
FETCH NEXT FROM myCursor into @S
WHILE @@FETCH_STATUS = 0
begin
set @xx1 = 'alter table #temp add ['+@s+'] varchar(5)'
execute sp_executesql @xx1
set @xx1 = 'update a set a.['+@s+'] = coalesce(b.counter,0) from #temp a, customers b where b.customertypeid = '+@s+' and a.state = b.state'
execute sp_executesql @xx1
FETCH NEXT FROM myCursor into @S
End
Close myCursor
DEALLOCATE myCursor
select * from #temp
Upvotes: 1
Reputation: 70648
This will do:
SELECT mainstate [State],
[1] type1,
[2] type2,
[3] type3
FROM ( SELECT mainstate, customertypeid, COUNT(1) [counter]
FROM customers
WHERE customertypeid in (1,2,3)
AND mainstate != ''
GROUP BY customertypeid, mainstate) as NonPivotedDataForReport2
PIVOT(SUM([counter]) FOR customertypeid IN ([1],[2],[3])) AS PivotedDataReport2
Upvotes: 3