以下是数据集。
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()OVER(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
答案 0 :(得分:2)
你很亲密。检查DEMO包含此查询,并从postgresql中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;
进行比较
{{1}}
答案 1 :(得分:1)
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;
这应该比相关子查询具有更好的性能。