如果使用pivot返回0行选择数据时如何设置NULL值?
;WITH cte AS (
SELECT
DATENAME(month, RPT.DateID) as Month,
ISNULL(SUM(RPT.TransactionIn), 0) as ATransactionIn,
ISNULL(SUM(RPT.TransactionOut), 0) as BTransactionOut,
ISNULL(SUM(RPT.OutstandingTransaction), 0) as COutstandingTransaction
FROM RPT_SummaryPOApproval RPT
WHERE RPT.Deleted = 0 --AND RPT.DivisionCode = 'asd'
GROUP BY DATENAME(month, RPT.DateID)
), pivoted
as
(
SELECT *
FROM (
SELECT [Month], [Transactions], [Values]
FROM (
SELECT *
FROM cte
) as p
UNPIVOT (
[Values] FOR [Transactions] IN (ATransactionIn, BTransactionOut, COutstandingTransaction )
) as unpvt
) as k
PIVOT (
MAX([Values]) FOR [Month] IN ([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])
) as pvt
)
SELECT * FROM pivoted
ORDER BY [Transactions] ASC
这些代码会产生如下结果:
Transaction January February March .... Dec
ATransactionIn 12 0 0 0
BTransactionOut 10 0 0 0
COutstandingTransaction 2 0 0 0
当我通过DivisionCode(在第一个代码上)取消注释Filter时
WHERE RPT.Deleted = 0 AND RPT.DivisionCode = 'asd'
结果就像这样
Transaction January February March .... Dec
如何显示这样的结果?
Transaction January February March .... Dec
ATransactionIn 0 0 0 0
BTransactionOut 0 0 0 0
COutstandingTransaction 0 0 0 0
答案 0 :(得分:1)
您可以对数据透视使用条件聚合:
WITH cte AS (
SELECT DATENAME(month, RPT.DateID) as Month,
SUM(CASE WHEN RPT.DivisionCode = 'asd' THEN RPT.TransactionIn ELSE 0 END) as ATransactionIn,
SUM(CASE WHEN RPT.DivisionCode = 'asd' THEN RPT.TransactionOut ELSE 0 END) as BTransactionOut,
SUM(CASE WHEN RPT.DivisionCode = 'asd' THEN RPT.OutstandingTransaction ELSE 0 END) as COutstandingTransaction
FROM RPT_SummaryPOApproval RPT
WHERE RPT.Deleted = 0
GROUP BY DATENAME(month, RPT.DateID)
), . . .
查询的其余部分应该相同。
答案 1 :(得分:0)
我解决了我的问题,当没有数据显示时,使用union显示0。
;WITH cte AS (
SELECT
DATENAME(month, RPT.DateID) as Month,
ISNULL(SUM(RPT.TransactionIn), 0) as ATransactionIn,
ISNULL(SUM(RPT.TransactionOut), 0) as BTransactionOut,
ISNULL(SUM(RPT.OutstandingTransaction), 0) as COutstandingTransaction
FROM RPT_SummaryPOApproval RPT
WHERE RPT.Deleted = 0 --AND RPT.DivisionCode = 'asd'
GROUP BY DATENAME(month, RPT.DateID)
UNION ALL
SELECT '0', '0', '0', '0'
), pivoted
as
(
SELECT *
FROM (
SELECT [Month], [Transactions], [Values]
FROM (
SELECT *
FROM cte
) as p
UNPIVOT (
[Values] FOR [Transactions] IN (ATransactionIn, BTransactionOut, COutstandingTransaction )
) as unpvt
) as k
PIVOT (
MAX([Values]) FOR [Month] IN ([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])
) as pvt
)
SELECT * FROM pivoted
ORDER BY [Transactions] ASC