简体   繁体   中英

Sql server select group by order by different field

I have a table:

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

I group by color and order by total and color:

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

So until herer, all is ok.

Now, I would want the same, but NOT ordering by color. I want to order by total, and then, by date. But I don't want to group by date.

Try this one -

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM