在sql中的子查询中使用group by

时间:2016-06-01 23:33:40

标签: sql subquery

如何解决此错误:

  

无法在。中使用的表达式中使用聚合或子查询   GROUP BY子句的GROUP BY列表。

这是我的查询:

select Id, name,dayA,monthA,yearA, 
    sum(x) as x,
    (select SUM(x) group by month) as total,
    from table_A
    group by Id,name,monthA,dAyA,yearA, SUM(x)

换句话说: 样本数据:

id name dayA monthA yearA  x
===========================
1  name1  2    3     2016   4
2  name2  2    3     2016   3
3  name1  2    3     2016   2      

预期结果:

id name dayA monthA yearA  x total
===================================
1  name1  2     3     2016  4  6
2  name2  2     3     2016  3  3 
3  name1  2     3     2016  2  6

提前致谢

3 个答案:

答案 0 :(得分:0)

您的查询有更多问题。

hash2.each do |nestling| nestling["activation_status"] = hash1[nestling["host"]] end ,它来自同一张桌子,不太可能因为你的小组月没有提到。在查询中使用子查询时,您必须保证我只返回一条记录。

根据您的样本数据和预期结果......

(select SUM(x) group by month) as total

答案 1 :(得分:0)

可能这就是你想要的:

select table_A.*, TotalSums.total
from table_A
left join (select name, monthA, dayA, yearA, sum(x) as total from table_A group by name, monthA, dayA, yearA) as TotalSums
    on table_A.name   = TotalSums.name
    and table_A.monthA = TotalSums.monthA
    and table_A.dayA = TotalSums.dayA
    and table_A.yearA = TotalSums.yearA
order by id

答案 2 :(得分:0)

我认为这就是你要找的东西

select Id, main.name,dayA,main.monthA,main.yearA, 
    sum(x) as x,
    ,max(total.total) as total
    from table_A as main
    join (select SUM(x) total ,name ,monthA,yearA from table_A group by name,monthA,yearA) as total
    on main.name = total.name
     and main.monthA = total.monthA
     and main.yearA = total.yearA
    group by Id,main.name,monthA,dAyA,yearA