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

Implement dense_rank() without using analytic function in Teradata

下面是数据集。

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

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

DENSE_RANK () OVER ( PARTITION BY c3 ORDER BY c3, c4 ) AS 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

你很接近。检查 DEMO 包括此查询和来自 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 确实支持 window 函数,只是不支持 dense_rank()(出于某种原因)。所以,我会使用 window 函数:

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;

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