SQL分组甚至奇怪

时间:2014-01-29 08:21:49

标签: sql oracle

我必须将某些数据分组,以便它有2套。

附加图像包含行为数据,预期结果和我使用的查询数据的详细信息。

我确信我错过了max option中的内容。请帮助enter image description here

  select agrmnt_id ,location_name, slab_no,target_start,target_end, tier_perc ,mod(RANK, 2) col from 
        (select agrmnt_id ,location_name, slab_no, target as target_start ,LAG(target) OVER (PARTITION BY location_name ORDER BY slab_no DESC)-1 as target_end  ,PAY_PREC|| '%' as tier_perc,
          DENSE_RANK() over(partition by agrmnt_id order by location_name) RANK
        from plb_addnl_slab_details 
        where agrmnt_id='PLBCAI140262' order by location_name,slab_no
        )) group by agrmnt_id,location_name ,slab_no
        order by location_name1 ,slab_no1,  location_name2 ,slab_no2

1 个答案:

答案 0 :(得分:0)

如果我理解你想要什么,这有点令人怀疑,看起来你能够生成一个你想要的所有值的列表,但你不能让它们在两个集合中对齐?如果是这样,我认为您需要将初始列表视为基本视图,并将其外部连接到自身,使用col值来确定哪个在第一个集合中,哪个在第二个集合中。

加入的标准似乎有点模糊。如果我添加另一个排名来阻止在第二列中出现两次的相同值,我可以用这个得到你期望的结果:

with t as (
  select agrmnt_id, location_name, slab_no, target_start, target_end,
    tier_perc , mod(col_rnk, 2) col, rnk
  from (
    select agrmnt_id, location_name, slab_no, target as target_start,
      LAG(target) OVER (PARTITION BY location_name
        ORDER BY slab_no DESC)-1 as target_end,
      SLAB_PERC|| '%' as tier_perc,
      DENSE_RANK() over(partition by agrmnt_id order by location_name) col_rnk,
      RANK() over(partition by agrmnt_id, slab_no order by location_name) rnk
    from plb_addnl_slab_details
    where agrmnt_id='PLBCAI140262'
  )
)
select t1.agrmnt_id as agrmnt_id_1, t1.location_name as location_name_1,
  t1.slab_no as slab_no_1, t1.target_start as target_start_1,
  t1.target_end as target_end_1,
  t2.agrmnt_id as agrmnt_id_2, t2.location_name as location_name_2,
  t2.slab_no as slab_no_2, t2.target_start as target_start_2,
  t2.target_end as target_end_2
from t t1
left join t t2 on t2.agrmnt_id = t1.agrmnt_id
and t2.slab_no = t1.slab_no
and t2.rnk = t1.rnk + 1
and t2.col = 0
where t1.col = 1
order by t1.agrmnt_id, t1.location_name, t1.slab_no;

SQL Fiddle。我不相信那些连接条件(或新排名)是完全正确的,但如果没有更多数据,或者有关您想要使用的逻辑的更多信息,则无法确定。希望这会给你一些你可以适应的东西。