oracle12c、sql、分组依据

qybjjes1  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(336)

原始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?

hgb9j2n6

hgb9j2n61#

我相信只要你把 col2 从您的选择和分组方式。因为 col2 将不再返回,还应删除having语句。我觉得应该是这样的:

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;

我希望这有帮助。

but5z9lq

but5z9lq2#

对col1使用sum()和group by

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
dy1byipe

dy1byipe3#

一个“简单”的选项是使用当前查询(重写为使用 JOIN s、 作为内联视图,这是目前连接表的首选方法:

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;

或者,移除 a.col2select :

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;

相关问题