GROUP BY但所有項目的總和

[英]GROUP BY but SUM of all items


We have a table for "trips". A trip is organized by a user. A trip can be viewed online by people. A trip can be part of a group of trips. Now, I want to get all trips by group but want to SUM the "views" of a trip at the same time.

我們有一張“旅行”表。旅行由用戶組織。人們可以在線查看旅行。旅行可以是一組旅行的一部分。現在,我希望按組進行所有旅行,但希望同時記錄旅行的“視圖”。

SELECT *, SUM(tripView) AS views 
FROM trip
WHERE tripGroup != 0
AND tripOrganizerUserId = '1'
GROUP BY tripGroup

With this, I get wrong numbers as "views". So how can I, in the query, without making a "SELECT SUM()" in every while-element, sum the views in this query?

有了這個,我得錯了數字作為“觀點”。那么,在查詢中,如果不在每個while元素中創建“SELECT SUM()”,如何在此查詢中對視圖求和?

1 个解决方案

#1


1  

As axiac points out in his comment, 'select *' and 'group by' in the same SQL statement is actually illegal. However, MySql's parser is broken when it comes to group by and allows it; I have no idea what it actually calculates but it's wrong.

正如他在評論中指出的那樣,在同一個SQL語句中,“select *”和“group by”實際上是非法的。但是,MySql的解析器在分組時被破壞並允許它;我不知道它實際計算的是什么,但這是錯誤的。

What you need to do is select what it needs to group by. So your SQL would be:

您需要做的是選擇分組所需的內容。所以你的SQL將是:

SELECT tripGroup, SUM(tripView) AS views 
FROM trip
WHERE tripGroup != 0
AND tripOrganizerUserId = '1'
GROUP BY tripGroup

MySql will parse this correctly, and should give you the answer you expect.

MySql將正確解析它,並應該給你你期望的答案。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/01/25/72effc5d5db35fb231201f761e093e98.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com