Using the distinct function in SQL

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

    As soulmerge and Shiraz have mentioned you'll need to use a GROUP BY and subselect. This worked for me.

    DECLARE @table TABLE (
        [Teacher] [NVarchar](256) NOT NULL ,
        [Student] [NVarchar](256) NOT NULL 
    )
    
    INSERT INTO @table VALUES ('Teacher 1', 'Student 1')
    INSERT INTO @table VALUES ('Teacher 1', 'Student 2')
    INSERT INTO @table VALUES ('Teacher 2', 'Student 3')
    INSERT INTO @table VALUES ('Teacher 2', 'Student 4')
    
    SELECT 
        T.[Teacher],  
        (
            SELECT TOP 1 T2.[Student]
            FROM @table AS T2 
            WHERE T2.[Teacher] = T.[Teacher]
        ) AS [Student]
    FROM @table AS T
    GROUP BY T.[Teacher]
    

    Results

    Teacher 1, Student 1
    Teacher 2, Student 3
    

提交回复
热议问题