P粉1558329412023-08-24 13:38:21
If you set disable ONLY_FULL_GROUP_BY
server mode (by default), your queries will run in MYSQL
. But in this case, you are using a different RDBMS. So to make your query work, add all non-aggregated columns to your GROUP BY
clause, like
SELECT col1, col2, SUM(col3) totalSUM FROM tableName GROUP BY col1, col2
Non-aggregated column means that the column will not be passed to aggregate functions, such as SUM
, MAX
, COUNT
, etc.
P粉0900872282023-08-24 10:30:14
Suppose I have the following tableT
:
a b -------- 1 abc 1 def 1 ghi 2 jkl 2 mno 2 pqr
I execute the following query:
SELECT a, b FROM T GROUP BY a
The output should have two lines, one for a=1
and the second for a=2
.
But what should the value of b be displayed in these two lines? There are three possibilities for each case, and nothing in the query makes it clear which value to choose for b in each group. The meaning is very vague.
This demonstrates the single value rule which prohibits getting undefined results when running a GROUP BY query and including any column criteria in the select list that is not part of the grouping and will not appear in in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x FROM T GROUP BY a
Now it's obvious that you want the following result:
a x -------- 1 ghi 2 pqr