使用where子句进行Pivot sql查询

时间:2017-06-30 11:57:09

标签: sql sql-server pivot where-clause

我有以下脚本来生成一个数据透视输出,但我正在努力解决2个元素:

1-输出显示输出,所有用户ID都在输出的左侧。

2-在脚本中放置一个限制输出的where子句。尝试了100种选择。任何帮助将不胜感激

SELECT 'invoices.USERID' AS totalvalue,
[1], [2]


FROM

(SELECT invoices.USERID, [total],PAYERCODE
FROM invoices
where invoices.userid = 41
  ) AS SourceTable

PIVOT
(
SUM([total])
FOR PAYERCODE IN ([1], [2])
) AS PivotTable;

enter image description here

所以我希望它看起来像是

enter image description here

任何帮助都会在我整个周末搞砸之前非常感激。

1 个答案:

答案 0 :(得分:1)

Y轴是一个字符串'invoices.USERID'

并删除WHERE invoices.userid = 41

SELECT USERID AS totalvalue,[1],[2]
FROM 
(SELECT invoices.USERID, [total],PAYERCODE
 FROM invoices
 --where invoices.userid = 41
) AS SourceTable
PIVOT
(
SUM([total])
FOR PAYERCODE IN ([1], [2])
) AS PivotTable;