按顺序分组

时间:2013-10-30 10:19:18

标签: sql sql-server

select aaa.BookId from
(SELECT     TOP (100) PERCENT Id, BookId,CreatedOnUtc
                       FROM          dbo.Chapter AS c
                       ORDER BY CreatedOnUtc desc             
                       ) as aaa
group by aaa.BookId

为什么ORDER BY CreatedOnUtc desc对结果没有任何影响。

我想得到像这样的结果

BookId    (with desc createdonUtc)
3
4
1
...

更新:我选择

select BookId, Max(CreatedOnUtc)
from Chapter
group by BookId
order by Max(CreatedOnUtc) desc

1 个答案:

答案 0 :(得分:2)

ORDER BY仅适用于您的子查询。您的外部查询没有order by子句,因此结果可以是任何顺序。

其他事项:

  • 为什么TOP 100 PERCENT
  • 为什么SELECT BookIdGROUP BY BookId但没有汇总列?也许你只想要SELECT DISTINCT

此外,您可能无法实现的目标。如果您的此表具有重复的BookId:

ID BookId CreatedOnUtc
1  1      1
2  2      2
3  1      3

你的结果会以什么顺序出现? 1 2或2 1?