Oracle SQL Developer Query从同一列返回2个值的计数

时间:2014-06-06 21:51:22

标签: sql oracle

我正在尝试计算列中两种类型事务的数量,如果没有则返回值0。该表是Transaction,我想要返回的列是帐号和列出的每个事务的计数列。这就是我所拥有的,但它没有运行:

SELECT 
ACCTNBR, 
COUNT(CASE when RTXNTYPCD='XDEP'then 1 else 0) AS Deposits,
COUNT(CASE when RTXNTYPCD='PWTH'then 1 else 0) AS Debits

FROM  
TRANSACTION 

WHERE 
((POSTDATE BETWEEN TO_DATE('05-01-2014','MM-DD-YYYY')) AND TO_DATE('05-31-2014','MM-DD-YYYY')) 

and ACCTNBR in ( 406,   1206,   1347,   4556,   6668,   9845)

GROUP BY 
ACCTNBR 

1 个答案:

答案 0 :(得分:1)

count函数会计算任何不是null的值。由于01都不是null,因此countsum都将返回表格中的总行数。相反,您应该使用SELECT ACCTNBR, SUM(CASE when RTXNTYPCD='XDEP' then 1 else 0 END) AS Deposits, SUM(CASE when RTXNTYPCD='PWTH' then 1 else 0 END) AS Debits FROM TRANSACTION WHERE ((POSTDATE BETWEEN TO_DATE('05-01-2014','MM-DD-YYYY')) AND TO_DATE('05-31-2014','MM-DD-YYYY')) and ACCTNBR in ( 406, 1206, 1347, 4556, 6668, 9845) GROUP BY ACCTNBR

{{1}}