我的表包含以下记录..表名:Cus1
Column: c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15
Records: 1 2 2 3 4 4 5 6 6 6 7 7 8 8 9 -1st record
1 2 3 3 3 4 4 5 5 5 5 6 7 7 8 -2nd record
如何使用上表获得如下结果:
Column: c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15
Records: 1 2 3 4 5 6 7 8 9 NULL NULL NULL NULL NULL NULL -1st record
1 2 3 4 5 6 7 8 NULL NULL NULL NULL NULL NULL NULL -2nd record
在DB2中使用if条件可能吗?
答案 0 :(得分:0)
不知道“使用条件”是什么意思,但也许以下内容可能会引起关注?
设定:
create table cus1
( c1 dec(3), c2 dec(3), c3 dec(3), c4 dec(3), c5 dec(3)
, c6 dec(3), c7 dec(3), c8 dec(3), c9 dec(3), c10 dec(3)
, c11 dec(3), c12 dec(3), c13 dec(3), c14 dec(3), c15 dec(3)
)
;
insert into cus1 values
( 1, 2, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7, 8, 8, 9)
, ( 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 7, 7, 8)
;
使用来自设置的表数据来生成查询;每个在这里创建的VIEW将被查询以获得最终结果:
create view cus1_unpivot_view as
with
cus1_rn as
( select row_number() over() as rn
, a.*
from cus1 a
)
SELECT rn, cn, cn_val
FROM cus1_rn as C
, lateral
( values ( 1, C.c1 ), ( 6, C.c6 ), ( 11, C.c11 )
, ( 2, C.c2 ), ( 7, C.c7 ), ( 12, C.c12 )
, ( 3, C.c3 ), ( 8, C.c8 ), ( 13, C.c13 )
, ( 4, C.c4 ), ( 9, C.c9 ), ( 14, C.c14 )
, ( 5, C.c5 ), ( 10, C.c10 ), ( 15, C.c15 )
) AS X( cn, cn_val )
; /* create an unpivot view of columns to rows */
create view cus1_unmatched as
select a.rn, a.cn, b.cn_val
from cus1_unpivot_view as a
left join
( select distinct rn, cn_val
from cus1_unpivot_view as d
) as b
on a.rn=b.rn
and a.cn=b.cn_val
; /* Generate unmatched values to get NULL results */
create view cus1_pivot as
select rn
, max( case when cn=1 then cn_val end ) as c1
, max( case when cn=2 then cn_val end ) as c2
, max( case when cn=3 then cn_val end ) as c3
, max( case when cn=4 then cn_val end ) as c4
, max( case when cn=5 then cn_val end ) as c5
, max( case when cn=6 then cn_val end ) as c6
, max( case when cn=7 then cn_val end ) as c7
, max( case when cn=8 then cn_val end ) as c8
, max( case when cn=9 then cn_val end ) as c9
, max( case when cn=10 then cn_val end ) as c10
, max( case when cn=11 then cn_val end ) as c11
, max( case when cn=12 then cn_val end ) as c12
, max( case when cn=13 then cn_val end ) as c13
, max( case when cn=14 then cn_val end ) as c14
, max( case when cn=15 then cn_val end ) as c15
from cus1_unmatched
group by rn
; /* pivot row data back to columns with the NULLs */
最后,查询最后一个VIEW以省略行编号并显示数据;将结果与期望的输出进行比较:
select
c1 , c2 , c3 , c4 , c5
, c6 , c7 , c8 , c9 , c10
, c11 , c12 , c13 , c14 , c15
from cus1_pivot
order by rn
; -- the following is a likeness of a report from the above query:
....+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8....+...
C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15
1 2 3 4 5 6 7 8 9 - - - - - -
1 2 3 4 5 6 7 8 - - - - - - -
******** End of data ********