2015-07-21 48 views
0

我嘗試在多列上執行彙總,然後在彙總過程的每個階段/部分上應用排名。結果應該看起來如下:SQL:將各個部分分開排列在多列上彙總

| ColA | ColB | ColC | RankingCriteria | Ranking | 
|------|------|------|-----------------|---------| 
| - | - | - | 10    | 1  | 
|------|------|------|-----------------|---------| 
| A | - | - | 10    | 1  | 
| B | - | - | 8    | 2  | 
|------|------|------|-----------------|---------| 
| A | a | - | 9    | 1  | 
| A | b | - | 7    | 2  | 
| A | c | - | 5    | 3  | 
| A | d | - | 2    | 4  | 
|------|------|------|-----------------|---------| 
| B | a | - | 8    | 1  | 
| B | c | - | 7    | 2  | 
| B | b | - | 2    | 3  | 
|------|------|------|-----------------|---------| 
| A | a | x | 7    | 1  | 
| A | a | y | 5    | 2  | 
| A | a | z | 4    | 3  | 
|------|------|------|-----------------|---------| 
| A | b | y | 6    | 1  | 
|------|------|------|-----------------|---------| 
| A | c | w | 10    | 1  | 
| A | c | y | 10    | 1  | 
| A | c | z | 8    | 2  | 
| A | c | x | 6    | 3  | 
|------|------|------|-----------------|---------| 
| A | d | y | 4    | 1  | 
|------|------|------|-----------------|---------| 
| B | a | w | 10    | 1  | 
| B | a | x | 8    | 2  | 
|------|------|------|-----------------|---------| 
| B | b | y | 6    | 1  | 
| B | b | z | 5    | 2  | 
| B | b | w | 4    | 3  | 
|------|------|------|-----------------|---------| 
| B | c | x | 6    | 1  | 
|------|------|------|-----------------|---------| 

因此,您可以看到每個分組集都有自己的排名。

這個基本的Rollup-Query很簡單,但排名讓我頭疼,而且我對如何實現這一點的想法很少。

Select ColA, ColB, ColC, RankingCriteria 
From table 
Group By Rollup(ColA, ColB, ColC) 

的問題是,我不能(通過...分區)使用了一個正常的排名()因爲沒有分區我可以使用,在整個事情會工作。

+0

你使用TSQL還是PLSQL? – Hiten004

回答

1

我認爲這會產生你想要什麼:

SELECT r.*, 
     row_number() over (partition by (case when colb is null and colc is null and cola is not null 
              then 1 else 0 end), 
             (case when colb is null and colc is null and cola is not null 
              then NULL else A end), 
             (case when colb is null and colc is null and cola is not null 
              then NULL else B end) 
         order by RankingCriteria desc) as seqnum       
FROM (Select ColA, ColB, ColC, RankingCriteria 
     From table 
     Group By Rollup(ColA, ColB, ColC) 
    ) r; 

我讀的邏輯的方法是通過一個是分區和B適用於所有,但第二組。這就是爲什麼這使用三個案例陳述。

+0

謝謝,你的回答幫助我完成了任務。我不得不修改它一點點。非常感謝你。 –