SELECT DISTINCT with LEFT JOIN, ORDERed BY in t-SQL

前端 未结 5 2066
悲哀的现实
悲哀的现实 2021-02-14 05:08

I have the following table in SQL Server 2008:

CREATE TABLE tbl (ID INT, dtIn DATETIME2, dtOut DATETIME2, Type INT)

INSERT tbl VALUES
(1, \'05:00\', \'6:00\', 1         


        
5条回答
  •  面向向阳花
    2021-02-14 06:08

    You were having this error because you didnot put (tbl.dtOut) in the select list.

    SELECT DISTINCT tbl.dtOut FROM tbl    
      LEFT JOIN tbl AS t1  
      ON tbl.type = t1.type AND  
         tbl.dtIn = t1.dtIn  
      ORDER BY tbl.dtOut ASC
    

    Will get you a result set (having 3 rows) and if you want the id field too then

    SELECT DISTINCT tbl.dtOut, tbl.ID FROM tbl      
      LEFT JOIN tbl AS t1  
      ON tbl.type = t1.type AND  
         tbl.dtIn = t1.dtIn  
      ORDER BY tbl.dtOut ASC  
    

    (having 6 rows, as it gives the distinct combination off id/date field)

提交回复
热议问题