我一直在纠结于多个计数语句
select distinct tam.sol_id||'|'||(select sol.sol_desc from sol where sol.sol_id=tam.sol_id)||'|'||count(*)||'|'||sum(org_tran_amt)
||'|'||count(case when ott.tran_date between '01-02-2021' and '24-02-2021' then 1 else 0 end)
from ott,tam
where tam.acid=ott.acid
and tam.gl_sub_head_code in ('85300','85320','85330','85340','85350','85360','85365','85370','85380','85390','85395')
and tran_date <= '24-02-2021'
and ott.del_flg='N'
and acct_cls_flg ='N'
and tam.sol_id in (select sst.sol_id from sst where sst.set_id='ROFPZ')
and not exists (select * from tct where tct.tran_date=ott.tran_date and trim(tct.tran_id)=trim(ott.tran_id)
and nvl(ott.org_tran_amt-tct.AMT_OFFSET,0)='0' and tct.entity_cre_flg='Y' and tct.del_flg='N')
) group by tam.sol_id;查询结果如下:
834|DH|1|2354|1
835|JA|3|4500|3
833|KO|4|3400|4输出不正确,因为最后一列计数必须小于第二列计数。
发布于 2021-02-24 16:24:05
当您使用count时,您会计算所有的not null值,无论它们是1、0还是其他值。例如,如下所示
SQL> select count(a), sum(a), count(b), sum(b)
2 from
3 (
4 select 1 as a, null as b from dual union all
5 select null as a, null as b from dual union all
6 select 0 as a, 0 as b from dual
7 );给出
COUNT(A) SUM(A) COUNT(B) SUM(B)
---------- ---------- ---------- ----------
2 1 1 0如果您的case提供1或0,那么您最好使用sum而不是count。另一种方法是编辑您的case,使其返回null而不是0,这样count就会像您期望的那样工作。
发布于 2021-02-24 20:53:52
你的问题很难理解。如果没有样本数据和期望的结果,你所遇到的任何问题都是不可能理解的。稍后我将讨论一个明显的问题。但首先:
永远不要在FROM子句中使用逗号。始终使用适当的、显式的、标准的、可读的JOIN格式。
使用标准JOIN格式的时间已经过去很久了。几十年来,SQL一直是JOIN标准的一部分。
您的代码中一个明显的问题是:
count(case when ott.tran_date between '01-02-2021' and '24-02-2021' then 1 else 0 end)首先,我会将日期格式修改为使用标准的YYYY-MM-DD格式。不过,更重要的是,您需要的是SUM()而不是COUNT()
sum(case when ott.tran_date between date '2021-02-01' and date '2021-02-24' then 1 else 0 end)COUNT(<expression>)统计表达式(或列)的非NULL值的数量。0和1一样都是NOT NULL,所以CASE对COUNT()没有任何作用。
https://stackoverflow.com/questions/66346302
复制相似问题