Using the distinct function in SQL

前端 未结 18 906
無奈伤痛
無奈伤痛 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:28

    distinct requires a unique result-set row. This means that whatever values you select from your table will need to be distinct together as a row from any other row in the result-set.

    Using distinct can return the same value more than once from a given field as long as the other corresponding fields in the row are distinct as well.

    0 讨论(0)
  • 2021-02-06 17:28

    You could use GROUP BY to separate the return values based on a single column value.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-02-06 17:33

    One option is to use a GROUP BY on Col A. Example:

    SELECT * FROM table_name GROUP BY Col A

    That should return you:

    abcd

    baac

    0 讨论(0)
  • 2021-02-06 17:33

    I'm not sure if I am understanding this right but couldn't you do

    SELECT * FROM class WHERE teacher IN (SELECT DISTINCT teacher FROM class)
    

    This would return all of the data in each row where the teacher is distinct

    0 讨论(0)
  • 2021-02-06 17:34

    You will need to say how your data is stored in-memory for us to say how you can query it.

    But you could do a separate query to just get the distinct teachers.

    select distinct teacher from class
    
    0 讨论(0)
提交回复
热议问题