2014-07-19 96 views
-1

我有兩個表(學生帳戶)
每個學生都有學生表中的一個記錄,但是可能會在帳戶表
我需要總結的帳戶表一列多條記錄,由學生代碼分組學生表
如何彙總連接表中的列?

我寫了下面的查詢,但是當我使用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

(1)這是mistagged的MySQL。這是其他一些RDMS。 (2)錯誤信息解釋你做錯了什麼。如果您不明白錯誤消息,請閱讀「GROUP BY」。 –

+0

我在查詢中看不到'students.id'。查詢是最新的嗎? –

回答

1

您需要按不屬於聚合的所有列進行分組。也就是說,如果students.stname在功能上依賴於students.stcode(即students.stcode是唯一的),則可以在students.stcode上應用聚合,例如max。由於account.stcode = students.stcode可以刪除。我不知道是什麼在從句應該在這裏做的,所以我刪除了一個,留給我們:

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:

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