且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用LEFT JOIN进行SELECT DISTINCT,在t-SQL中按ORDER BY

更新时间:2023-02-05 22:50:20

当您缩小单个ID的范围时,您就有可能每个ID可能会有更多与其关联的一个dtOut。发生这种情况时,Sql Server将如何知道要使用哪个顺序?

When you narrow it down 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?

您可以尝试:

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

但是,正如我上面提到的如果匹配的ID大于右侧表中的记录,则可以多次列出具有相同ID的可能性。

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 record on the right-side table.