私は次のクエリのピボットを作成しようとしています:
select mainstate, customertypeid, count(1) as [counter] from customers group by customertypeid, mainstate
このクエリは、州ごとに同じ数の顧客タイプを表示する必要があります。次のようになります(順序は関係ありません):
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
*追記:CASE+SUMステートメントに戻りたくありません。
どうもありがとう!