我有sql代码,我希望COLUMN1中的每个唯一值都是相同的rownum。 例如,在示例中,我想要rownum 2,3和第2列rownum 2的空值
select rownum,
t1.column1 as column1,
t1.Column2 as column2,
t3.Column3 as column3
from Table1 t1,Table3 t3,Table2 t2
where t3.S_ID=t2.AS_ID
and t2.KT_ID=t1.T_ID
我该如何实现?
答案 0 :(得分:2)
首先,学习正确的显式join
语法。其次,您可以使用lag()
和其他分析函数轻松完成所需的操作:
select (case when column1 = lag(column1) over (order by column1, column3)
then NULL
else dense_rank() over (order by column1)
end) as rn,
t1.column1 as column1,
t1.Column2 as column2,
t3.Column3 as column3
from Table1 t1 join
Table2 t2
on t2.KT_ID = t1.T_ID join
Table3 t3
on t3.S_ID = t2.AS_ID
order by column1, column3;
一些注意事项:
order by
。column3
到排序。它可以是使稳定排序的任何列。也就是说,每一行都有一组唯一的订单键,因此每次都有相同的顺序。lag()
函数使用相同的排序条件,但column1
仅使用dense_rank()
。join
语法。它更强大,几乎每个人都认为它更容易阅读。答案 1 :(得分:0)
This might help you...
select rownum,column1,column2,column3 from (
Select rownum,column1,column2,column3,
row_number() over( partition by column1,column2 order by column1,column2) as analytic_rnm
from(
select rownum,
column1 as column1,
Column2 as column2,
Column3 as column3
from Table1 t1,Table3 t3,Table2 t2
where t3.S_ID=t2.AS_ID
and t2.KT_ID=t1.T_ID
)X
)M
where analytic_rnm=1
union all
select NULL as rownum,
column1,column2,column3 from (
Select rownum,column1,column2,column3,
row_number() over( partition by column1,column2 order by column1,column2) as analytic_rnm
from(
select rownum,
column1 as column1,
Column2 as column2,
Column3 as column3
from Table1 t1,Table3 t3,Table2 t2
where t3.S_ID=t2.AS_ID
and t2.KT_ID=t1.T_ID
)X)Y
where analytic_rnm>1
答案 2 :(得分:0)
select
case when row_number() -- if it's the first row per group...
over(partition by column1
order by column3) = 1
then dense_rank() -- ... return 1,2,3
over(order by column1)
else null
end,
t1.column1 as column1,
t1.Column2 as column2,
t3.Column3 as column3
from Table1 t1,Table3 t3,Table2 t2
where t3.S_ID=t2.AS_ID
and t2.KT_ID=t1.T_ID