SELECT top 5
day_description,
count(numberofdays) as number
FROM mytable
where department = 'departmentname'
group by day_description
我的选择会带来这样的东西:
day description number
holiday 32
working day 212
training day 5
meeting day 26
admin day 66
是否有一种方法可以添加一个新列,其中1-5位为最高值,1为最高值行,5为最低值行。看起来像这样:
day description number top5ID
holiday 32 3
working day 212 1
training day 5 5
meeting day 26 4
admin day 66 2
答案 0 :(得分:5)
也许是这样的:
;WITH CTE
AS
(
SELECT top 5
day_description,
count(numberofdays) as number
FROM mytable
where department = 'departmentname'
group by day_description
)
SELECT
ROW_NUMBER() OVER(ORDER BY CTE.number DESC) AS Top5ID,
CTE.*
FROM
CTE
或没有CTE:
SELECT
ROW_NUMBER() OVER(ORDER BY t.number DESC) AS Top5ID,
t.*
FROM
(
SELECT top 5
day_description,
count(numberofdays) as number
FROM mytable
where department = 'departmentname'
group by day_description
) AS t
答案 1 :(得分:1)
所以,你可以使用它:
SELECT TOP 5 day_description, COUNT(numberofdays) AS number,
ROW_NUMBER() OVER(ORDER BY COUNT(numberofdays) DESC) AS Top5ID
FROM mytable
WHERE department = 'departmentname'
GROUP BY day_description
ORDER BY COUNT(numberofdays) DESC