我尝试在多个列上执行Rollup,然后对Rollup过程的每个阶段/部分应用排名。结果应该如下所示:
| 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)
问题是我不能使用正常的Rank()除以(Partition by…),因为没有分区可以用于整个事情
我想这会产生你想要的效果:
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;
我读逻辑的方式是,划分A和B适用于除了第二组。这就是为什么这里使用了三个case语句。