Using the distinct function in SQL

前端 未结 18 1284
無奈伤痛
無奈伤痛 2021-02-06 16:55

I have a SQL query I am running. What I was wanting to know is that is there a way of selecting the rows in a table where the value in on one of those columns is distinct? When

18条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 17:31

    You have misunderstood the DISTINCT keyword. It is not a function and it does not modify a column. You cannot SELECT a, DISTINCT(b), c, DISTINCT(d) FROM SomeTable. DISTINCT is a modifier for the query itself, i.e. you don't select a distinct column, you make a SELECT DISTINCT query.

    In other words: DISTINCT tells the server to go through the whole result set and remove all duplicate rows after the query has been performed.

    If you need a column to contain every value once, you need to GROUP BY that column. Once you do that, the server now needs to do which student to select with each teacher, if there are multiple, so you need to provide a so-called aggregate function like COUNT(). Example:

    SELECT teacher, COUNT(student) AS amountStudents
    FROM ...
    GROUP BY teacher;
    

提交回复
热议问题