我的结果目前返回以下内容:
+----+-------+-------+-------+
| ID | item1 | item2 | item3 |
+----+-------+-------+-------+
| 1 | 1 | 0 | 1 |
| 2 | 0 | 1 | 1 |
| 3 | 1 | 1 | 1 |
+----+-------+-------+-------+
我希望他们成为:
+-----------+
| ID | item |
+-----------+
| 1 | item1 |
| 1 | item3 |
| 2 | item2 |
| 2 | item3 |
| 3 | item1 |
| 3 | item2 |
| 3 | item3 |
+-----------+
重组数据是否可能?
非常感谢任何帮助!
答案 0 :(得分:1)
一种方法是使用union all
来创建结果:
with t as (
<yourqueryhere>
)
select id, 'item1' as item from t where item1 > 0 union all
select id, 'item2' as item from t where item2 > 0 union all
select id, 'item3' as item from t where item3 > 0;
根据对查询的修改,可能还有另一种更简单的解决方案。但是,如果不知道查询是什么,就不可能这样说。
答案 1 :(得分:1)
一种方法是使用cross join
和case
这样的 unpivoting 技巧:
select
id, item
from (
select
t.id,
case
when x.i = 1 and item1 = 1 then 'item1'
when x.i = 2 and item2 = 1 then 'item2'
when x.i = 3 and item3 = 1 then 'item3'
end as item
from your_table t
cross join (
select 1 i union all
select 2 i union all
select 3 i
) x
) t where item is not null;
注意:此方法读取表格一次。
答案 2 :(得分:0)
select id,item
from td_unpivot
(
on ({put your query here})
using value_columns ('val')
unpivot_column ('item')
column_list ('item1','item2','item3')
) u
where val = 1
order by id,item
+----+-------+
| ID | item |
+----+-------+
| 1 | item1 |
| 1 | item3 |
| 2 | item2 |
| 2 | item3 |
| 3 | item1 |
| 3 | item2 |
| 3 | item3 |
+----+-------+