从单个表在Oracle中返回0,带计数的值

时间:2018-07-09 04:34:22

标签: sql oracle

所以我有一张名为Vouchers的表:

ID_ENTITY -> Unique Key
ID_VOUCHER 
VOUCHER_CODE
AMNT_VOUCHER_DENOM
ID_VOUCHER_STATUS
DAT_EXPIRE_DATE

我有一个计数查询:

select count(*),AMNT_VOUCHER_DENOM,ID_VOUCHER 
from CUS_VOUCHERS
where ID_VOUCHER_STATUS = 0 
and ID_VOUCHER = 1 
and trunc(DAT_EXPIRE_DATE) >= trunc(sysdate)
group by AMNT_VOUCHER_DENOM,ID_VOUCHER;

结果:

-----------------------------------------
COUNT | AMNT_VOUCHER_DENOM |  ID_VOUCHER
1     |100000              |1
      |                    |

预期结果:

----------------------------------------
COUNT | AMNT_VOUCHER_DENOM  | ID_VOUCHER
1     | 100000              |1
0     |150000               |1
0     |200000               |1

实际上我有很多AMNT_VOUCHER_DENOMID_VOUCHER = 1,但还有ID_VOUCHER_STATUS != 0

我该怎么办?

2 个答案:

答案 0 :(得分:3)

删除ID_VOUCHER_STATUS上的过滤器,并使用case语句对感兴趣的项目进行计数

select count(case when ID_VOUCHER_STATUS = 0 then 1 end) as no_of_sts_0
       , AMNT_VOUCHER_DENOM,ID_VOUCHER 
from CUS_VOUCHERS
where ID_VOUCHER = 1 
and trunc(DAT_EXPIRE_DATE) >= trunc(sysdate)
group by AMNT_VOUCHER_DENOM,ID_VOUCHER;

这里是a SQL Fiddle demo

答案 1 :(得分:0)

WHERE ID_VOUCHER_STATUS = 0 and ID_VOUCHER = 1将排除所有AMNT_VOUCHER_DENOMID_VOUCHER_STATUS != 0

因此您要执行:

select count(*),AMNT_VOUCHER_DENOM,ID_VOUCHER from CUS_VOUCHERS
where ID_VOUCHER = 1 and trunc(DAT_EXPIRE_DATE) >= trunc(sysdate)
group by AMNT_VOUCHER_DENOM,ID_VOUCHER;`