【问题标题】:Sql server select group by order by different fieldSql server 按不同字段的顺序选择组
【发布时间】:2013-04-27 10:21:09
【问题描述】:

我有一张桌子:

Id    Date        color
------------------------- 
 1    23/04/2013  red
 2    23/04/2013  white
 3    23/04/2013  yellow
 4    23/04/2013  red
 5    23/04/2013  orange
 6    23/04/2013  blue
 7    23/04/2013  yellow
 8    23/04/2013  red

我按颜色分组,按总数和颜色排序:

Select top 5 color, count(color) as total from table where Date<=getdate() group by color order by total desc, color asc

所以到这里为止,一切都很好。

现在,我想要同样的,但不按颜色排序。我想按总数排序,然后按日期排序。但我不想按日期分组。

【问题讨论】:

  • 问题是哪个日期,因为有多个日期。德瓦特给出了一个非常合理的答案。 . .如果您同意,您应该接受答案。
  • 是的,对我来说已经足够了。我如何接受或投票?

标签: sql sql-server group-by sql-order-by


【解决方案1】:

试试这个 -

DECLARE @temp TABLE
(
      Id INT IDENTITY(1,1)
    , [Date] DATETIME
    , color NVARCHAR(50)
)

INSERT INTO @temp ([Date], color)
VALUES 
    ('20130423',  'red'),
    ('20130422',  'white'),
    ('20130423',  'yellow'),
    ('20130423',  'red'),
    ('20130425',  'orange'),
    ('20130423',  'blue'),
    ('20130423',  'yellow'),
    ('20130423',  'red')

SELECT TOP 5 color, total = COUNT(color)  
FROM @temp 
WHERE [Date] <= GETDATE() 
GROUP BY color 
ORDER BY total DESC, MAX([Date])

【讨论】:

  • +1 不知道 SQL Server 在 order by 子句中允许使用别名
  • 不客气@onbermejo。如果此解决方案完全适合您,如果您能确认,我将很高兴。
猜你喜欢
  • 2016-11-12
  • 2012-08-01
  • 2017-06-02
  • 2013-06-13
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多