Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何汇总联接表中的列?_Sql_Sql Server - Fatal编程技术网

Sql 如何汇总联接表中的列?

Sql 如何汇总联接表中的列?,sql,sql-server,Sql,Sql Server,我有两张桌子(学生和会计) 每个学生在学生表中有一条记录,但在科目表中可能有多条记录 我需要汇总account表中的一列,按students表中的students code分组 我编写了以下查询,但当我使用GROUP BY命令时,它返回了一个错误: select students.id,students.stcode,students.stname,account.stcode, sum(cast ((account.price) AS INT)) OVER () AS Price

我有两张桌子(学生和会计)
每个学生在学生表中有一条记录,但在科目表中可能有多条记录
我需要汇总account表中的一列,按students表中的students code分组

我编写了以下查询,但当我使用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
错误消息:

列“students.id”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中

您需要按不属于聚合的所有列进行分组。也就是说,如果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
另一个选项是将students.stname包含在group by子句中:

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 

(1) 这是错误标记的MySQL。这是其他一些RDM。(2) 错误消息解释了您做错了什么。如果您不理解错误消息,请阅读关于
分组依据的内容
。我在查询中没有看到
students.id
。查询是最新的吗?