Using the distinct function in SQL

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

    Based on the limited details you provided in your question (you should explain how/why your data is in different tables, what DB server you are using, etc) you can approach this from 2 different directions.

    1. Reduce the number of columns in your query to only return the "teacher" and "email" columns but using the existing WHERE criteria. The problem you have with your current attempt is both DISTINCT and GROUP BY don't understand that you one want 1 row for each value of the column that you are trying to be distinct about. From what I understand, MySQL has support for what you are doing using GROUP BY but MSSQL does not support result columns not included in the GROUP BY statement. If you don't need the "student" columns, don't put them in your result set.

    2. Convert your existing query to use column based sub-queries so that you only return a single result for non-grouped data.

    Example:

    SELECT t1.a
            , (SELECT TOP 1 b FROM Table1 t2 WHERE t1.a = t2.a) AS b
            , (SELECT TOP 1 c FROM Table1 t2 WHERE t1.a = t2.a) AS c
            , (SELECT TOP 1 d FROM Table1 t2 WHERE t1.a = t2.a) AS d
        FROM dbo.Table1 t1
        WHERE (your criteria here)
        GROUP BY t1.a
    

    This query will not be fast if you have a lot of data, but it will return a single row per teacher with a somewhat random value for the remaining columns. You can also add an ORDER BY to each sub-query to further tweak the values returned for the additional columns.

提交回复
热议问题