oracle12c,sql,分组依据
oracle12c,sql,group by
原来的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?
我相信只要从 select 中删除 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;
希望对您有所帮助。
使用 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
“简单”选项是使用您当前的查询(重写为使用 JOIN
s,这是现在 joining 表的首选方式)作为内联视图:
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;
原来的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?
我相信只要从 select 中删除 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;
希望对您有所帮助。
使用 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
“简单”选项是使用您当前的查询(重写为使用 JOIN
s,这是现在 joining 表的首选方式)作为内联视图:
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;