首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sql查询中的多条count语句

sql查询中的多条count语句
EN

Stack Overflow用户
提问于 2021-02-24 15:18:05
回答 2查看 33关注 0票数 0

我一直在纠结于多个计数语句

代码语言:javascript
复制
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;

查询结果如下:

代码语言:javascript
复制
834|DH|1|2354|1
835|JA|3|4500|3
833|KO|4|3400|4

输出不正确,因为最后一列计数必须小于第二列计数。

EN

回答 2

Stack Overflow用户

发布于 2021-02-24 16:24:05

当您使用count时,您会计算所有的not null值,无论它们是10还是其他值。例如,如下所示

代码语言:javascript
复制
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  );

给出

代码语言:javascript
复制
  COUNT(A)     SUM(A)   COUNT(B)     SUM(B)
---------- ---------- ---------- ----------
         2          1          1          0

如果您的case提供10,那么您最好使用sum而不是count。另一种方法是编辑您的case,使其返回null而不是0,这样count就会像您期望的那样工作。

票数 0
EN

Stack Overflow用户

发布于 2021-02-24 20:53:52

你的问题很难理解。如果没有样本数据和期望的结果,你所遇到的任何问题都是不可能理解的。稍后我将讨论一个明显的问题。但首先:

永远不要在FROM子句中使用逗号。始终使用适当的、显式的、标准的、可读的JOIN格式。

使用标准JOIN格式的时间已经过去很久了。几十年来,SQL一直是JOIN标准的一部分。

您的代码中一个明显的问题是:

代码语言:javascript
复制
count(case when ott.tran_date between '01-02-2021' and '24-02-2021' then 1 else 0 end)

首先,我会将日期格式修改为使用标准的YYYY-MM-DD格式。不过,更重要的是,您需要的是SUM()而不是COUNT()

代码语言:javascript
复制
sum(case when ott.tran_date between date '2021-02-01' and date '2021-02-24' then 1 else 0 end)

COUNT(<expression>)统计表达式(或列)的非NULL值的数量。01一样都是NOT NULL,所以CASECOUNT()没有任何作用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66346302

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档