我有一个包含每个事务类型的事务金额的大表(数百万个rec)。我正在尝试获取每个事务类型的COUNT,其中金额大于,小于等于0.我正在执行3个单独的查询来获取此信息,更改每个中的WHERE子句然后将结果一起分块之后。
有人可以推荐一种更聪明的方式来撰写这个声明吗?
伪
SELECT
TRANSACTION_CD
,COUNT(TRANSACTION_CD)
FROM [FINANCIAL_TRANSACTION] ft
INNER JOIN POLICY p ON p.POLICY_ID = ft.POLICY_ID
WHERE
ft.EFFECTIVE_DT > '01/01/2008'
AND SIGN(ft.transaction_amt) = -1
GROUP BY
TRANSACTION_CD
ORDER BY
TRANSACTION_CD
答案 0 :(得分:4)
SELECT
TRANSACTION_CD
,SUM(CASE WHEN ft.transaction_amt < 0 THEN 1 ELSE 0 END) AS NegativeCount
,SUM(CASE WHEN ft.transaction_amt = 0 THEN 1 ELSE 0 END) AS ZeroCount
,SUM(CASE WHEN ft.transaction_amt > 0 THEN 1 ELSE 0 END) AS PositiveCount
FROM [FINANCIAL_TRANSACTION] ft
INNER JOIN POLICY p ON p.POLICY_ID = ft.POLICY_ID
WHERE
ft.EFFECTIVE_DT > '01/01/2008'
GROUP BY
TRANSACTION_CD
ORDER BY
TRANSACTION_CD