SQL Server - T-SQL UNION ALL + PIVOT

时间:2016-05-10 17:43:07

标签: c# sql sql-server tsql

有没有办法可以PIVOT以下SQL查询,这样我就可以将每个查询中的3个不同的列名保留为1行。目前,它从第一个查询中将结果显示为1行列名下的3行。

SELECT COUNT(sdo.Id) AS [TotalNew] FROM [SubscriberDebitOrder] sdo WHERE sdo.[CampaignId]=@p0 AND sdo.[CreatedOn] >= 
(
   SELECT CAST(MAX(sdo.[CreatedOn]) AS DATE) FROM [SubscriberDebitOrder] sdo WHERE sdo.[CampaignId]=@p0
)
UNION ALL
SELECT COUNT(sdo.Id) AS [TotalNewSuccess] FROM [SubscriberDebitOrder] sdo 
INNER JOIN [Collections] c ON c.[DebitOrderId]=sdo.[Id]
WHERE sdo.[CampaignId]=@p0 AND sdo.[CreatedOn] >= 
(
   SELECT CAST(MAX(sdo.[CreatedOn]) AS DATE) FROM [SubscriberDebitOrder] sdo WHERE sdo.[CampaignId]=@p0
) AND c.TxnStatus='S'
UNION ALL
SELECT COUNT(sdo.Id) AS [TotalNewFailed] FROM [SubscriberDebitOrder] sdo 
INNER JOIN [Collections] c ON c.[DebitOrderId]=sdo.[Id]
WHERE sdo.[CampaignId]=@p0 AND sdo.[CreatedOn] >= 
(
   SELECT CAST(MAX(sdo.[CreatedOn]) AS DATE) FROM [SubscriberDebitOrder] sdo WHERE sdo.[CampaignId]=@p0
) AND c.TxnStatus='U'

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以将查询简化为以下内容。

SELECT 
 COUNT(*) AS [TotalNew]
,sum(case when c.TxnStatus='S' then 1 else 0 end) as [TotalNewSuccess]
,sum(case when c.TxnStatus='U' then 1 else 0 end) as [TotalNewFailed]
FROM [SubscriberDebitOrder] sdo 
INNER JOIN [Collections] c ON c.[DebitOrderId]=sdo.[Id]
WHERE sdo.[CampaignId]=@p0 
AND sdo.[CreatedOn] >= 
(
 SELECT CAST(MAX([CreatedOn]) AS DATE) 
 FROM [SubscriberDebitOrder]
 WHERE [CampaignId] = @p0
)