您好,登錄后才能下訂單哦!
DB2行列轉(zhuǎn)置的行轉(zhuǎn)列是怎樣的,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
建表,并insert 2行數(shù)據(jù)
CREATE TABLE SalesAgg(year INTEGER, q1 INTEGER, q2 INTEGER, q3 INTEGER, q4 INTEGER);
insert into SalesAgg values(2004,20,30,15,10);
insert into SalesAgg values(2005,18,40,12,27);
Select * from SalesAgg
YEAR Q1 Q2 Q3 Q4
---- -- -- -- --
2004 20 30 15 10
2005 18 40 12 27
想把數(shù)據(jù)轉(zhuǎn)成下面的樣子
YEAR QUARTER RESULTS
---- ------- -------
2004 1 20
2004 2 30
2004 3 15
2004 4 10
2005 1 18
2005 2 40
2005 3 12
2005 4 27
列轉(zhuǎn)換成行的SQL
SELECT Year, Quarter, Results
FROM SalesAgg AS S,
LATERAL(VALUES(1, S.q1),
(2, S.q2),
(3, S.q3),
(4, S.q4))
AS Q(Quarter, Results);
LATERAL的地方可以換成TABLE,結(jié)果一樣,其目的都是通過(guò)VALUES值來(lái)組合成一個(gè)臨時(shí)表Q在SQL中使用
SELECT Year, Quarter, Results
FROM SalesAgg AS S,
TABLE(VALUES(1, S.q1),
(2, S.q2),
(3, S.q3),
(4, S.q4))
AS Q(Quarter, Results);
另外一個(gè)使用TABLE的例子
SELECT id ANSWER
,salary AS sal
,comm AS com
,combo
,typ
FROM staff
,TABLE (
VALUES (
salary
,'SAL'
)
,(
comm
,'COM'
)
) AS tab(combo, typ)
WHERE id < 40
ORDER BY id
,typ;
行轉(zhuǎn)列使用示例
CREATE OR REPLACE PROCEDURE DB2INST1.TEST(OUT out_msg VARCHAR(4000))
SPECIFIC DB2INST1.TEST
MODIFIES SQL DATA
NOT DETERMINISTIC
NULL CALL
LANGUAGE SQL EXTERNAL ACTION
INHERIT SPECIAL REGISTERS
BEGIN
DECLARE v_col1s VARCHAR(4000);
DECLARE v_sql VARCHAR(4000);
SELECT SUBSTR(XMLCAST(XMLGROUP(',' || col1 AS a ORDER BY col1) as varchar(4000)),2) into v_col1s FROM aaa;
SET out_msg = 'SELECT * FROM aaa where col1 in (' || TRIM(v_col1s) || ')';
看完上述內(nèi)容,你們掌握DB2行列轉(zhuǎn)置的行轉(zhuǎn)列是怎樣的的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。