oracle12c,sql,分组依据

Posted

技术标签:

【中文标题】oracle12c,sql,分组依据【英文标题】:oracle12c,sql,group by 【发布时间】:2020-07-09 09:26:56 【问题描述】:

原来的sql是:

select c.col1,a.col2,count(1) from table_1 a,table_2 b.table_3 c where a.key =b.key and b.no = c.no group by c.col1,a.col2 having count(a.col2) >1;

输出:

c.col1  a.col2 count(1)
aa1     bb1    2
aa1     bb2    3
aa1     bb3    5
aa2     bb8    1
aa2     bb1    4

我尝试获取输出集,就像

c.col1   count(1)
aa1        10
aa2        5

sql怎么写?

【问题讨论】:

【参考方案1】:

“简单”选项是使用您当前的查询(重写为使用JOINs,这是当今加入表的首选方式)作为内联视图:

  SELECT col1, SUM (cnt)
    FROM (  SELECT c.col1, a.col2, COUNT (*) cnt     --> your current query begins here
              FROM table_1 a
                   JOIN table_2 b ON a.key = b.key
                   JOIN table_3 c ON c.no = b.no
          GROUP BY c.col1, a.col2
            HAVING COUNT (a.col2) > 1)               --> and ends here
GROUP BY col1;

或者,从select 中删除a.col2

  SELECT c.col1, COUNT (*) cnt
    FROM table_1 a
         JOIN table_2 b ON a.key = b.key
         JOIN table_3 c ON c.no = b.no
GROUP BY c.col1, a.col2
  HAVING COUNT (a.col2) > 1;

【讨论】:

【参考方案2】:

我相信,如果您只需从您的选择和分组依据中删除 col2,您就可以做到这一点。因为col2 将不再返回,您还应该删除have 语句。我认为它应该看起来像这样:

select
    c.col1,
    count(1)
from
    table_1 a,
    table_2 b,
    table_3 c
where
    a.key = b.key
    and b.no = c.no
group by
    c.col1;

我希望这会有所帮助。

【讨论】:

在这种情况下,您可以添加:拥有 count(1)>1【参考方案3】:

使用 sum() 并且只对 col1 进行分组

select c.col1, sum(a.col2) as total
    from table_1 a,table_2 b.table_3 c 
    where a.key =b.key and b.no = c.no 
    group by c.col1;

输出---

c.col1   total
aa1        10
aa2        5

【讨论】:

有语句是重点!~~

以上是关于oracle12c,sql,分组依据的主要内容,如果未能解决你的问题,请参考以下文章

分组依据 - SQL Oracle 错误:无效项目

Oracle SQL 行到具有分组依据和总和的列

ORACLE1.26 综合:游标和动态SQL

理解Oracle体系结构 并在CentOS 7 上安装Oracle 12c

无效的请求“分组依据”(oracle)

sql 获取分组第一行数据