我一直在试图创建以下查询枢轴:在一组通过查询
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声明,
非常感谢!
+1:该死,打我吧。这是正确的答案。 – 2013-02-26 20:17:25
谢谢,这项工作的魅力。 – 2013-02-26 20:25:52
@AngelEscobedo听起来不错:-) – Lamak 2013-02-26 20:26:26