在不使用 Teradata 中的分析函数的情况下实现 dense_rank()



下面是数据集。

select * from temp_denserow;
c1  c2  c3  c4
103 1   3   1
204 1   3   2
102 1   3   3
304 1   1   3
203 1   2   1
104 1   2   2
300 3   1   2
201 1   2   2
301 2   1   4
302 2   4   4
303 1   4   3
101 1   3   2
202 1   2   3

我正在使用 teradata,其中没有内置的 dense_rank(( 函数。

DENSE_RANK (( 超过(按 C3 顺序划分 C3, C4 ( 作为new_dense_rank

我尝试实现上述语句,但无法获得所需的输出。

select emp.*,
(select count(distinct c3)
from temp_denserow emp2
where emp2.c3 = emp.c3 and
emp2.c4 >= emp.c4
) as "new_dense_rank"
from temp_denserow emp;

预期产出:

301 2   1   4   3
304 1   1   3   2
300 3   1   2   1
202 1   2   3   3
104 1   2   2   2
201 1   2   2   2
203 1   2   1   1
102 1   3   3   3
204 1   3   2   2
101 1   3   2   2
103 1   3   1   1
302 2   4   4   2
303 1   4   3   1

你很接近。检查演示包括此查询和来自 postgresql 的DENSE_RANK进行比较

select emp.*,
(select count(distinct c4)
from temp_denserow emp2
where emp2.c3 = emp.c3 and
emp2.c4 >= emp.c4
) as "new_dense_rank"
from temp_denserow emp
ORDER BY c3, c4 DESC;

Teradata确实支持窗口函数,只是不支持dense_rank()(出于某种原因(。 因此,我会使用窗口函数:

select emp.*,
sum(case when seqnum = 1 then 1 else 0 end) over (partition by emp.c3 order by emp.c4 rows between unbounded preceding and current row) as new_dense_rank
from (select emp.*,
row_number() over (partition by emp.c3, emp.c4 order by emp.c4) as seqnum
from temp_denserow emp
) emp;

这应该比相关子查询具有更好的性能。

相关内容

最新更新