这是我的表,我会使用解码在日常场景中显示以下值,但是,我需要在特定报告的1列中显示所有值,因为它们对应于同一项目。
T1:
Id V1 V2 V3 V4 V5 V5_Text
1 1 1 1 0 0 Other
2 0 1 1 0 1 Other
3 0 0 1 0 1 QWE
4 0 0 1 1 0 ABC
5 1 0 0 0 1 Other
我曾经使用过case,但我似乎无法返回超过1的值。
select id,
case when V1=1, then 'A'
when V2=1, then 'B'
when V3=1, then 'C'
when V4=1, then 'D'
when V5=1, then v5_text
预期产出:
1 A,B,C,Other
2 B,C,Other
3 C,QWE
4 C,D,ABC
5 A,Other
实际输出:
1 Other
2 Other
3 QWE
4 ABC
5 Other
答案 0 :(得分:3)
您需要连接值:
select id,
trim(',' from
(case when V1 = 1 then 'A,' end) ||
case when V2 = 1 then 'B,' end) ||
case when V3 = 1 then 'C,' end) ||
case when V4 = 1 then 'D,' end) ||
case when V5 = 1 then v5_text
)
)
答案 1 :(得分:0)
不确定你还有什么想法,这个表有多大,但另一种方法是“取消”v1 ... v5结构,然后使用listagg()
btw:第一行
Id V1 V2 V3 V4 V5 V5_Text
1 1 1 1 0 0 Other
A B C -- there is no "other" here
Oracle 11g R2架构设置:
CREATE TABLE Table1
(ID int, V1 int, V2 int, V3 int, V4 int, V5 int, V5_TEXT varchar2(5))
;
INSERT ALL
INTO Table1 (ID, V1, V2, V3, V4, V5, V5_TEXT)
VALUES (1, 1, 1, 1, 0, 0, 'Other')
INTO Table1 (ID, V1, V2, V3, V4, V5, V5_TEXT)
VALUES (2, 0, 1, 1, 0, 1, 'Other')
INTO Table1 (ID, V1, V2, V3, V4, V5, V5_TEXT)
VALUES (3, 0, 0, 1, 0, 1, 'QWE')
INTO Table1 (ID, V1, V2, V3, V4, V5, V5_TEXT)
VALUES (4, 0, 0, 1, 1, 0, 'ABC')
INTO Table1 (ID, V1, V2, V3, V4, V5, V5_TEXT)
VALUES (5, 1, 0, 0, 0, 1, 'Other')
SELECT * FROM dual
;
查询1 :
select
id, listagg(alpha,',') within group (order by alpha) codes_concat
from (
select id, v1, V5_TEXT, 'A' alpha from table1 where v1 = 1 union all
select id, v2, V5_TEXT, 'B' alpha from table1 where v2 = 1 union all
select id, v3, V5_TEXT, 'C' alpha from table1 where v3 = 1 union all
select id, v4, V5_TEXT, 'D' alpha from table1 where v4 = 1 union all
select id, v5, V5_TEXT, 'Other' from table1 where v5 = 1
) d
group by
id
<强> Results 强>:
| ID | CODES_CONCAT |
|----|--------------|
| 1 | A,B,C |
| 2 | B,C,Other |
| 3 | C,Other |
| 4 | C,D |
| 5 | A,Other |
修改强>
如果联盟都冒犯了,那么还有其他方法:
select
id, listagg(alpha,',') within group (order by alpha) codes_concat
from (
select
id
, V5_TEXT
, case when cj.n = 1 then v1
when cj.n = 2 then v2
when cj.n = 3 then v3
when cj.n = 4 then v4
when cj.n = 5 then v5 end v1
, case when cj.n = 1 then 'A'
when cj.n = 2 then 'B'
when cj.n = 3 then 'C'
when cj.n = 4 then 'D'
when cj.n = 5 then V5_TEXT end alpha
from table1
cross join (
Select level n from dual connect by level<=5
) cj
) d
where v1 <> 0
group by
id
;
或者可以使用unpivot等。
select
id, listagg(alpha,',') within group (order by alpha) codes_concat
from (
select
id, v5_text, v1
, case when vname = 'V1' then 'A'
when vname = 'V2' then 'B'
when vname = 'V3' then 'C'
when vname = 'V4' then 'D'
when vname = 'V5' then v5_text end alpha
from table1
UNPIVOT (
v1 FOR( vname ) IN ( v1, v2, v3, v4, v5
)
)
) d
where v1 <> 0
group by
id
;
答案 2 :(得分:0)