2015-07-21 47 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

谢谢,你的回答帮助我完成了任务。我不得不修改它一点点。非常感谢你。 –