如何汇总连接表中的列?

时间:2014-07-19 15:18:58

标签: sql sql-server

我有两张桌子(学生和帐户)
每个学生在学生表中都有一条记录,但在帐户表中可能有多条记录 我需要在帐户表中汇总一列,按学生表中的学生代码分组

我编写了以下查询,但是当我使用GROUP BY命令时,它返回了一个错误:

select students.id,students.stcode,students.stname,account.stcode,
       sum(cast ((account.price) AS INT)) OVER () AS PriceTotal
from students 
inner join account on students.stcode=account.stcode 
group by students.stcode

错误消息:
Column 'students.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

1 个答案:

答案 0 :(得分:1)

您需要按不属于聚合的所有列进行分组。也就是说,如果students.stname在功能上依赖于students.stcode(即students.stcode是唯一的),您可以在students.stcode上应用max等聚合。由于account.stcode = students.stcode可以删除。我不确定over子句应该在这里做什么,所以我删除了那个,留下我们:

select students.stcode, max(students.stname) as stname
     , sum(cast (account.price AS INT)) AS PriceTotal
from students 
join account 
    on students.stcode=account.stcode 
group by students.stcode

另一种选择是在group by子句中包含students.stname:

select students.stcode, students.stname
     , sum(cast (account.price AS INT)) AS PriceTotal
from students 
join account 
    on students.stcode=account.stcode 
group by students.stcode, students.stname

如果您使用的是支持窗口功能的DBMS(您标记帖子的mysql没有),则不需要按以下组分组:

select students.stcode, students.stname
     , sum(cast (account.price AS INT)) over () AS PriceTotal
from students 
join account 
    on students.stcode=account.stcode