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

前端 未结 5 2042
悲哀的现实
悲哀的现实 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:07

    When you narrow it down to individual id's, you create the possibility that each id might have more than one dtOut associated with it. When that happens, how will Sql Server know which order to use?

    You could try:

    SELECT t1.id
    FROM tbl t1
    LEFT JOIN  tbl t2 on t1.type = t2.type AND t1.dtIn = t2.dtIn
    GROUP BY t1.id, t2.dtOut
    ORDER BY t2.dtOut
    

    However, as I mentioned above this can open the possibility of having the same id listed more than once, if it matches to more than one record on the right-side table.

提交回复
热议问题