我写了这样的SQL查询。
SELECT
TR.TRAN_DATE,
CASE WHEN tr.CR_DR='CR' THEN sum(TR.GL_TRN_AMT) ELSE 0 END AS CR,
CASE WHEN tr.CR_DR='DR' THEN sum(TR.GL_TRN_AMT) ELSE 0 END AS DR
FROM
[COREBANKER1].[dbo].[GL_DAILY_TRN] AS TR
WHERE
TR.GL_CODE = '01010101'
AND TR.BRANCH_CODE = 1000
AND TR.TRAN_DATE BETWEEN '2016-11-01' AND '2017-03-01'
GROUP BY
TR.TRAN_DATE, TR.CR_DR, TR.[BRANCH_CODE]
ORDER BY
TR.TRAN_DATE
结果如下:
但我想将DR CR结果放在一行。
答案 0 :(得分:2)
进行条件聚合时,case
是sum()
:
SELECT TR.TRAN_DATE,
SUM(CASE WHEN tr.CR_DR = 'CR' THEN TR.GL_TRN_AMT ELSE 0
END) AS CR,
SUM(CASE WHEN tr.CR_DR='DR' THEN TR.GL_TRN_AMT ELSE 0
END) AS DR
FROM [COREBANKER1].[dbo].[GL_DAILY_TRN] TR
WHERE TR.GL_CODE = '01010101' AND
TR.BRANCH_CODE=1000 AND
TR.TRAN_DATE BETWEEN '2016-11-01' AND '2017-03-01'
GROUP BY TR.TRAN_DATE --, TR.[BRANCH_CODE]
ORDER BY TR.TRAN_DATE;
我不知道你是否想为每个分支分别设置一行。如果您这样做,请取消注释GROUP BY
中的引用。