SQL 选择不同的不按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9572131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
select distinct not working as expected
提问by sriram
Student group table:
学生组表:
STDNT_GROUP
studentId,CollegeID,studentgroup,flag
1,007,panthers,y
2,003,owls,n
3,007,owls,y
1,007,texans,y
2,003,texans,n
Expected output
预期输出
1,007
2,003
3,007
I want unique student ids as well as their respective college ids.
我想要唯一的学生 ID 以及他们各自的大学 ID。
I tried this query:
我试过这个查询:
select distinct(studentId),collegeID from;
and
和
select studentId,collegeID from STDNT_GROUP where studentId in(select distinct(studentId) from STDNT_GROUP)";
回答by Michael Berkowski
Using DISTINCT
without parentheses should get you what you want. DISTINCT
should be thought of as a clause, rather than a function to which you pass a column name as an argument. It returns the set of distinct rowsover the superset returned by the query, rather than distinct values in a single column.
使用DISTINCT
不带括号应该可以得到你想要的。 DISTINCT
应该被认为是一个子句,而不是一个将列名作为参数传递给的函数。它返回查询返回的超集上的一组不同行,而不是单个列中的不同值。
SELECT DISTINCT
studentId,
CollegeID
FROM STUDENT_GROUP
回答by Mosty Mostacho
You could use this for unsorted results:
您可以将其用于未排序的结果:
select distinct studentid, collegeid from stdnt_group
Or this:
或这个:
select studentid, collegeid from stdnt_group
group by studentid, collegeid
Or you could add an order by clause to any of them to retrieve them in order:
或者您可以向其中任何一个添加 order by 子句以按顺序检索它们:
[previous query]
order by studentid, collegeid
回答by Spags
The issue may be your use of paranthesis in the distinct call. Try just:
问题可能是您在不同的调用中使用了括号。试试吧:
SELECT DISTINCT studentID, collegeID
It may be helpful to provide what output you are actually getting as opposed to just the expected output. That may help us better determine whatmay be going wrong.
提供您实际获得的输出而不是仅提供预期输出可能会有所帮助。这可能有助于我们更好地确定可能出了什么问题。