true
我希望来自此查询的年月明智数据具有相应的[待定],[通讯],[确认],[已取消],[失败]交易计数。基本上我希望待定,通过,确认,取消和失败的月份交易计数。
我正在使用Sql Server 2016 现在我得到的确切数据,但是几个月被列出两次或三次。
我想要以下格式的数据
if [[ $a = true ]];
请帮我查询此类查询或任何其他查询。
答案 0 :(得分:0)
您可以尝试将现有查询放在Common Table Expression内,然后将GROUP BY
放在年份和月份中,同时汇总数字。
WITH preselect AS
(
SELECT * FROM (
SELECT YEAR(CreateDate) [Year], MONTH(CreateDate) [Month], DATENAME(MONTH,CreateDate) [Month Name],COUNT(id) [Total],
CASE
WHEN PaymentStatus = 1 THEN 'Pending'
WHEN PaymentStatus = 2 THEN 'Commited'
WHEN PaymentStatus = 3 THEN 'Confirmed'
WHEN PaymentStatus = 4 THEN 'Canceled'
WHEN PaymentStatus = 5 THEN 'Failed'
ELSE ''
END AS PaymentStatus,count(ID) as counts
FROM [dbo].[BankPaymentRequest]
GROUP BY YEAR(CreateDate), MONTH(CreateDate), DATENAME(MONTH, CreateDate), PaymentStatus) as asd
PIVOT( SUM(counts)
FOR PaymentStatus IN ([Pending],[Commited],[Confirmed],[Canceled],[Failed])) AS MNamePivot
)
SELECT [YEAR],[MONTH],SUM(TOTAL)'TOTAL',SUM(Pending)'Pending'
,SUM(Commited)'Commited',SUM(Confirmed)'Confirmed'
,SUM(Canceled)'Canceled',SUM(Failed)'Failed'
FROM preselect
GROUP BY [YEAR],[MONTH]