2012-05-02 60 views
2
SELECT top 5 
day_description, 
count(numberofdays) as number 

FROM mytable 

where department = 'departmentname' 

group by day_description 

我的選擇帶來了這樣的回:添加號ID爲表

day description   number   
holiday      32    
working day     212    
training day    5     
meeting day     26    
admin day     66 

有沒有添加新的列,其中它asigns或者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

什麼版本你使用的是sql-server嗎? – Arion

+0

你的目標是什麼?知道哪一排更高? –

+0

我在SSRS BIDS中使用它來生成條形圖,我希望能夠根據它們的前5位指定每個條的顏色。 – JsonStatham

回答

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 
+2

雖然把最高值設置爲5而不是1 – JsonStatham

+0

對此很抱歉。我更新了答案。請再次測試:P – Arion

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