我有以下查询,我使用PIVOT显示结果,以便结果显示在一行中。
With T1 As
(EXT Code
),
T2 AS (
SELECT p.SId, p.TransType, Amount =SUM(p.Amount)
FROM T1 p
GROUP BY p.SId, p.TransType
)
SELECT m.SNo, m.Name, t.TransType,
CASE WHEN t.TransType ='PAYCM' THEN t.Amount ELSE 0 END AS 'GROSS CM',
CASE WHEN t.TransType ='PAYYTD' THEN t.Amount ELSE 0 END AS 'GROSS YTD',
CASE WHEN t.TransType ='TAXCM' THEN t.Amount ELSE 0 END AS 'Tax CM',
CASE WHEN t.TransType ='TAXYTD' THEN t.Amount ELSE 0 END AS 'Tax YTD'
FROM Master m INNER JOIN T2 t ON t.PId = m.Id
答案 0 :(得分:1)
如果您想要一行,请使用聚合并删除非聚合列:
SELECT SUM(CASE WHEN t.TransType = 'PAYCM' THEN t.Amount ELSE 0 END) AS GROSS _CM,
SUM(CASE WHEN t.TransType = 'PAYYTD' THEN t.Amount ELSE 0 END) AS GROSS_YTD,
SUM(CASE WHEN t.TransType = 'TAXCM' THEN t.Amount ELSE 0 END) AS Tax_CM,
SUM(CASE WHEN t.TransType = 'TAXYTD' THEN t.Amount ELSE 0 END) AS Tax_YTD
FROM Master m INNER JOIN
T2 t
ON t.PId = m.Id;