带有order by和Top Distinct的SQL

时间:2017-01-24 15:19:50

标签: sql sql-order-by distinct

SELECT distinct TOP 100 
event.[ExtId],
event.[EventId],
event.[StateId]
FROM
(
SELECT CS.[Id],
CS.[ExternalId],
CS.[EventId],
CS.[StateId]
FROM CS
ORDER BY CS.[Id] asc
) event

提出错误,在SQL中说Order BY Clause子句在视图中无效等等......执行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

由于GROUP BY

,您需要使用ORDER BY
SELECT TOP 100 e.[ExtId], e.[EventId], e.[StateId]
FROM (SELECT DISTINCT CS.[Id], CS.[ExternalId], CS.[EventId], CS.[StateId]
      FROM CS
     ) e
GROUP BY e.[ExtId], e.[EventId], e.[StateId]
ORDER BY MIN(CS.[Id]);

我认为这完全等同于:

SELECT TOP 100 CS.[ExternalId], CS.[EventId], CS.[StateId]
FROM CS
GROUP BY CS.[ExternalId], CS.[EventId], CS.[StateId]
ORDER BY MIN(CS.[Id]);

这是编写逻辑的更典型方式。