使rownum值在相同的值中为null

时间:2015-10-24 10:45:15

标签: sql oracle

我有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

enter image description here

我该如何实现?

3 个答案:

答案 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;

一些注意事项:

  • SQL查询返回无序结果集。如果您希望按特定顺序排序 - 或者下次运行查询时按相同顺序排列 - 那么请添加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