不知道什麼意思是「使用條件」,但也許下面可能有興趣?
設置:
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)
;
從設置到生成的查詢使用表中的數據;每個在這裏創建作爲視圖要查詢的最終結果:
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 */
最後,查詢該最後一個視圖省略行編號和呈現數據;將結果與期望的輸出進行比較:
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 ********
您的問題很不清楚,令人困惑。提供您的業務邏輯 - 不要讓我們猜測。 – MichaelTiefenbacher
您好邁克爾, 在下面我的表具有值lkie 山口C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15 Val' 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企業需要使用上表輸出並得到如下結果 Col c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 Val 1 2 3 4 5 6 7 8 9 你能幫我解決這個問題嗎? – YAK
描述業務需求 - 不是「像下面」。順便提一下,17個值不適合15列。 – MichaelTiefenbacher