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

前端 未结 5 2053
悲哀的现实
悲哀的现实 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 05:54

    You can use only those columns in ORDER BY clause which are part of your select statement when you use 'DISTINCT' key word. So you can order only by tbl.id

    If ids are unique, DISTINCT keyword doesn't make any sense and will cause performance degradation and you can just remove it. In case they are not and you decide to select tbl.dtOut as well while keeping DISTINCT, the pair tbl.id and tbl.dtOut can give you multiple entries having same tbl.id which is probably not desired.

    Check this article for possible workarounds and explanation why such queries are prohibited.

提交回复
热议问题