[英]Oracle SQL group by returns multiple rows
Here is my table这是我的桌子
And here comes my query (Oracle SQL):这是我的查询(Oracle SQL):
SELECT col_1, sum(col_2)
FROM table
GROUP BY col_1
I then expect to have as result:然后我希望有结果:
But, outcome of this query is:但是,这个查询的结果是:
This is unexpected behavior from my understanding.据我了解,这是出乎意料的行为。 Indeed, it seems that SQL consider col_3 to calculate result.
确实,似乎 SQL 考虑 col_3 来计算结果。 But, to me, col_3 is not selected so it should not be taken into consideration to group by data.
但是,对我来说, col_3 没有被选中,所以不应该考虑按数据分组。
I may have missed how to proceed with such cases.我可能错过了如何处理此类案件。
Thanks in advance for your help to build up my knowledge:)提前感谢您帮助我积累知识:)
You probably have a trailing whitespace character (or an zero-width character) in one row.您可能在一行中有一个尾随空白字符(或零宽度字符)。
CREATE TABLE table_name (col_1, col_2, col_3) AS
SELECT 'A', 1, 'X' FROM DUAL UNION ALL
SELECT 'A ', 1, 'Y' FROM DUAL UNION ALL -- Note the trailing space!
SELECT 'A', 2, 'X' FROM DUAL UNION ALL
SELECT 'B', 1, 'X' FROM DUAL UNION ALL
SELECT 'C', 1, 'X' FROM DUAL;
Then:然后:
SELECT col_1, DUMP(col_1) FROM table_name;
Outputs:输出:
COL_1 ![]() |
DUMP(COL_1)![]() |
---|---|
A![]() |
Typ=1 Len=1: 65![]() |
A![]() |
Typ=1 Len=2: 65,32![]() |
A![]() |
Typ=1 Len=1: 65![]() |
B![]() |
Typ=1 Len=1: 66![]() |
C ![]() |
Typ=1 Len=1: 67![]() |
You can see that the 2nd row has an extra character with the ASCII code 32 (which is a space character).您可以看到第二行有一个额外的字符,ASCII 码为 32(这是一个空格字符)。
And:和:
SELECT col_1,
sum(col_2)
FROM table_name
GROUP BY col_1;
Outputs:输出:
COL_1 ![]() |
SUM(COL_2)![]() |
---|---|
B |
1 ![]() |
A |
1 ![]() |
C |
1 ![]() |
A |
3 ![]() |
Where there is, correctly, an A
and an A
group.正确地,有一个
A
和一个A
组。
If you want to ignore the trailing space then:如果您想忽略尾随空格,则:
SELECT RTRIM(col_1) AS col_1,
sum(col_2)
FROM table_name
GROUP BY RTRIM(col_1);
COL_1 ![]() |
SUM(COL_2)![]() |
---|---|
B![]() |
1 ![]() |
C ![]() |
1 ![]() |
A![]() |
4 ![]() |
Or else, UPDATE
the table to remove the trailing spaces from col_1
.否则,
UPDATE
表以从col_1
中删除尾随空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.