Za7*_*7pi 2 sql sql-server group-by sql-order-by
我有一张桌子:
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
Run Code Online (Sandbox Code Playgroud)
我按颜色和顺序按总和颜色分组:
Select top 5 color, count(color) as total from table where Date<=getdate() group by color order by total desc, color asc
Run Code Online (Sandbox Code Playgroud)
所以直到这里,一切都好.
现在,我想要相同,但不按颜色排序.我想按总数排序,然后按日期排序.但我不想按日期分组.
试试这个 -
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])
Run Code Online (Sandbox Code Playgroud)