简体   繁体   中英

oracle12c,sql,group by

the original sql is:

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;

the output:

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

i try to get the output set which is like

c.col1   count(1)
aa1        10
aa2        5

how to write the sql?

I believe you can do that if you simply remove col2 from your select and group by. Because col2 will no longer be returned, you should also remove the having statement. I think it should look something like this:

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;

I hope this helps.

A "simple" option is to use your current query (rewritten to use JOIN s, which is nowadays preferred way of joining tables) as an inline view:

  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;

Or, remove a.col2 from select :

  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;

use sum() and only group by for the 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;

Output---

c.col1   total
aa1        10
aa2        5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM