SQL数据透视表语法

时间:2014-02-28 15:43:24

标签: sql sql-server-2008

我有以下查询:

SELECT 
  INT_AUX_CONTACT.CONTACT_VISIBILITY_IND,
     INT_USER.ACCOUNT_NM

FROM (INT_USER 
INNER JOIN INT_AUX_CONTACT_COLLECTION      ON "INT_USER"."USER_ID"="INT_AUX_CONTACT_COLLECTION".IA_USER_ID) 
INNER JOIN INT_AUX_CONTACT  ON INT_AUX_CONTACT_COLLECTION.COLLECTION_ID=INT_AUX_CONTACT.COLLECTION_ID
WHERE INT_AUX_CONTACT_COLLECTION.COLLECTION_TYP_ID=1 AND INT_AUX_CONTACT.DELETED_IND=0
and ACTIVE_IND=1

返回以下结果示例:

contact_visibility_ind|account_nm
1                      HR05
2                      HR05
3                      HR05
3                      HR05
2                      HR05
1                      CH10
2                      CH10
3                      CH10
4                      CH10
0                      CH10
2                      CH10

我想生成一个带有结果表的数据透视表,如下所示:

           0  1  2  3  4
CH10  0  1  2  2  0
HR05  1  1  2  1  1

但每次我尝试使用pivot功能时,我都会遇到语法错误。

有人有什么建议吗? (抱歉,我的桌子上没有网格线!)

1 个答案:

答案 0 :(得分:0)

我不是100%肯定你是如何得到数据透视表的最终推导的。我假设你想要计算每次出现的次数(可能CH10HR05应该在表格中交换?)

SELECT account_nm, [0], [1], [2], [3], [4]
FROM
(SELECT * 
 FROM 
 ResultOfQuery
) x
PIVOT
(
  COUNT(contact_visibility_ind)
  FOR contact_visibility_ind IN ([0], [1], [2], [3], [4])
) y;

Fiddle here

只需将您的查询粘贴到SELECT * FROM ResultOfQuery占位符。