2013-02-26 118 views
0

我一直在試圖創建以下查詢樞軸:在一組通過查詢

select mainstate, customertypeid, count(1) as [counter] from customers group by customertypeid, mainstate 

此查詢應顯示每個國家儘可能多的客戶類型,它看起來像這樣(ORDER BY沒有按」牛逼事):

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 

我試着使用PIVOT如下(我敢肯定,我錯了):

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 

我得到這個:

customertypeid|type1|type2|type3 
     1   0  0  0 
     2   0  0  0 
     3   0  0  0 

,報告應該是這樣的:

State|type1|type2|type3 
UT  20 100 200 
CA  50 200 500 
NY  30 120 300 

* PS:我真的不想回去CASE + SUM聲明,

非常感謝!

回答

3

這樣做:

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 
+0

+1:該死,打我吧。這是正確的答案。 – 2013-02-26 20:17:25

+0

謝謝,這項工作的魅力。 – 2013-02-26 20:25:52

+0

@AngelEscobedo聽起來不錯:-) – Lamak 2013-02-26 20:26:26

1

這(可能稍微改動過),應該爲你做的工作不區分/和/支點。創建臨時表,插入起始數據,然後根據有多少個客戶類型ID來動態添加列。

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 ['[email protected]+'] varchar(5)' 
     execute sp_executesql @xx1 
      set @xx1 = 'update a set a.['[email protected]+'] = coalesce(b.counter,0) from #temp a, customers b where b.customertypeid = '[email protected]+' and a.state = b.state' 
      execute sp_executesql @xx1 
     FETCH NEXT FROM myCursor into @S 
    End 
Close myCursor 
DEALLOCATE myCursor 

select * from #temp 
+0

如果您知道前面的列並且客戶ID不變,Lamak的答案是更簡單的方法。如果您事先並不瞭解這些列,那麼動態添加列將是您的方式。 – JohnZ 2013-02-26 20:20:02