Confusion about SELECT DISTINCT in SQL

谁说我不能喝 提交于 2019-12-11 19:21:19

问题


When I select COLUMN_1 only I get the right amount of 8 rows in my database because it doesn't give me duplicate rows and its what I want

SELECT DISTINCT COLUMN_1
FROM TABLE
WHERE COLUMN_3=12;

but when select both COLUMN_1, COLUMN_2 it gives me 53 rows in my database and that's not what I want...

SELECT DISTINCT COLUMN_1,COLUMN_2
FROM TABLE
WHERE COLUMN_3=12;

I know when I select two columns with distinct, it will give me unique values for the combination of the two columns. DISTINCT is applied to the combination of the columns, not just the first column. So my question is how do I select both COLUMN_1 and COLUMN_2 so that they give me 8 rows and no duplicates ???? because as soon as I add COLUMN_2 it gives more rows that I am supposed to have..


回答1:


You have to decide which value for column_2 you want.

One simple way is a group by:

SELECT COLUMN_1, min(COLUMN_2)
FROM TABLE
WHERE COLUMN_3=12
GROUP BY COLUMN_1;



回答2:


I'm not totally clear on your exact requirements but a nice solution here could be to use some king of aggregation function that prevents the duplication but still returns all of the values from the column causing the duplication e.g.

The following data,

COLUMN1 | COLUMN2
-----------------
a       | x
b       | x
c       | y
a       | z
b       | y
a       | y

Would be displayed as,

COLUMN1 | COLUMN2
-----------------
a       | x,z,y
b       | x,y
c       | y

You don't specify the database you are using but in Oracle you could use the LISTAGG function which could be something like the following in your case:

SELECT COLUMN1,
       LISTAGG(COLUMN2, ',') WITHIN GROUP (ORDER BY COLUMN2) "COLUMN2_VALUES",
  FROM TABLE

If you're not using Oracle, and this sounds like a suitable solution, then it's worth checking if you RDBMS of choice provides something similar.



来源:https://stackoverflow.com/questions/18792815/confusion-about-select-distinct-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!