SELECT code_value FROM attributes attr WHERE attr.id = 6662 AND
attr.code IN ('ATTRIBUTE_CODE_1',
'ATTRIBUTE_CODE_2',
'ATTRIBUTE_CODE_3',
'ATTRIBUTE_CODE_4',
'ATTRIBUTE_CODE_5')
ORDER BY code_value
结果的强度可能会有所不同(0-5因为某些属性不存在):
示例结果:
CODE_VALUE
---------------
CODE_FOR_ATTR_1
CODE_FOR_ATTR_4
CODE_FOR_ATTR_5
我只需要一行:
CODE_1 CODE_2 CODE_3 CODE_4 CODE_5
-------------------------------------------------------------------------------------
CODE_FOR_ATTR_1 CODE_FOR_ATTR_4 CODE_FOR_ATTR_5 NULL NULL
最好的方法是什么?
答案 0 :(得分:2)
只要保留相对顺序,您似乎不关心各种代码出现在哪些列中,但您想要将最多五行压缩为一行:
with dta as (
select code_value
, row_number() over (partition by id order by code_value) rn
from attributess attr
where 1=1
and attr.id = 6662
and attr.code in ('ATTRIBUTE_CODE_1',
'ATTRIBUTE_CODE_2',
'ATTRIBUTE_CODE_3',
'ATTRIBUTE_CODE_4',
'ATTRIBUTE_CODE_5')
)
select *
from dta
pivot (max(code_value)
FOR rn IN ( 1 code_1
, 2 code_2
, 3 code_3
, 4 code_4
, 5 code_5))