将数据从一列拆分为多个其他列

时间:2013-05-17 11:06:32

标签: sql sybase

我遇到了一个问题,我正在使用的其中一个表格设置方式使我很难达到我的需要。

index_name  und_mnem   weight     percent_wt  undId   altId     type       
'.SXXP'      'AAL.L'  0.051341648  0.015464   18742  '08238P911 'CUS'
'.SXXP'      'AAL.L'  0.051341648  0.015464   18742  '32508392' 'ISIN'

我需要将这两行合并为一行,标题为CUS和ISIN,相应列中的正确altId。

理想情况下,数据看起来像这样

index_name  und_mnem   weight     percent_wt  undId     Cus        ISIN      
'.SXXP'      'AAL.L'  0.051341648  0.015464   18742  '08238P911 '32508392'

这是我的查询

SELECT 
    il.index_name, il.und_mnem, il.weight, il.percent_wt, il.index_shares, 
    il.undId, aa.altId, aa.type 
FROM 
    indexlist il 
join 
    altIdentifier aa on aa.id = il.undId 
where 
    il.index_name = ".SXXP" and type in ("ISIN","CUS")

我正在使用Sybase

非常感谢任何帮助!

谢谢,

2 个答案:

答案 0 :(得分:0)

select il.index_name, il.und_mnem, il.weight, il.percent_wt, il.index_shares, 
        il.undId, cusTbl.cus,isinTbl.isin
from indexlist il join
(select il.undId,aa.altId as cus 
from indexlist il 
    join 
        altIdentifier aa on aa.id = il.undId 
    where 
        il.index_name = ".SXXP" and type="CUS") as cusTbl on il.undId=cusTbl.undId
join
(select il.undId,aa.altId as isin 
from indexlist il 
    join 
        altIdentifier aa on aa.id = il.undId 
    where 
        il.index_name = ".SXXP" and type="ISIN") as isinTbl on il.undId=isinTbl.undId

答案 1 :(得分:0)

您应该能够使用带有CASE表达式的聚合函数来获得结果:

SELECT  il.index_name, 
  il.und_mnem, 
  il.weight, 
  il.percent_wt, 
  il.index_shares, 
  il.undId, 
  max(case when aa.type = 'CUS' then aa.altId end) Cus,
  max(case when aa.type = 'ISIN' then aa.altId end) ISUN
FROM indexlist il 
join altIdentifier aa 
  on aa.id = il.undId 
where il.index_name = ".SXXP" 
  and type in ("ISIN","CUS")
group by il.index_name, il.und_mnem, il.weight, il.percent_wt, 
  il.index_shares, il.undId