原始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?
发布于 2020-07-09 09:53:08
“简单”选项是将当前查询(重写为使用JOIN,这是当今连接表的首选方式)作为内联视图使用:
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.col2中删除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;发布于 2020-07-09 09:49:44
我相信,如果您只需从select和group中删除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;我希望这能帮到你。
发布于 2020-07-09 09:51:41
对col1使用sum()和只组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 5https://stackoverflow.com/questions/62811717
复制相似问题