在DB2

时间:2019-02-20 15:25:02

标签: db2

有没有一种方法可以在一行中显示某些列值,然后显示其余的列?我已经写了下面的查询,它给出了3行作为输出,但是它只能带来1条输出。

select asset.assetnum, asset.serialnum, assetspec.alnvalue , assetspec.assetattrid  
from asset  
left outer join  assetspec on asset.assetnum = assetspec.assetnum  
and asset.classstructureid = assetspec.classstructureid  
where asset.assetnum='100' AND assetspec.ASSETATTRID IN ('XXX','YYY','ZZZ')

输出

ASSETNUM   SERIALNUM    ALNVALUE  ASSETATTRID
100            123         A         XXX
100            123         B         YYY
100            123         C         ZZZ 

预期产量

ASSETNUM   SERIALNUM    XXX    YYY   ZZZ
 100          123         A      B    C

1 个答案:

答案 0 :(得分:0)

尝试一下:

with tab (ASSETNUM, SERIALNUM, ALNVALUE, ASSETATTRID) as (values
  (100, 123, 'A', 'XXX')
, (100, 123, 'B', 'YYY')
, (100, 123, 'C', 'ZZZ')
)
select ASSETNUM, SERIALNUM
, max(case ASSETATTRID when 'XXX' then ALNVALUE end) as XXX
, max(case ASSETATTRID when 'YYY' then ALNVALUE end) as YYY
, max(case ASSETATTRID when 'ZZZ' then ALNVALUE end) as ZZZ
from tab
group by ASSETNUM, SERIALNUM;