我正在处理的数据集示例是:
ColA ColB ColC ColD ColE ColF ColG ColH ColI ColJ ColK ColL ColM X1 5 X2 6 X3 5 X4 4 X5 5 X6 3 X7
带数字的列表示ids,其余表示值等。
我想从id
之后的单元格中提取值.5。如果查看示例,可以看到id
5不断重复。我需要提取单元格的最新值。因此,在这种情况下它应该是'X6'。
你能帮我写一个针对这个问题的SQL查询吗?
谢谢你, Nimish
答案 0 :(得分:2)
使用CASE
表达式并按相反的顺序遍历列:
Oracle 11g R2架构设置:
CREATE TABLE table_name ( ColA, ColB, ColC, ColD, ColE, ColF, ColG, ColH, ColI, ColJ, ColK, ColL, ColM ) As
SELECT 'X1', '5', 'X2', '6', 'X3', '5', 'X4', '4', 'X5', '5', 'X6', '3', 'X7' FROM DUAL
查询1 :
SELECT CASE
WHEN ColL = '5' THEN ColM
WHEN ColK = '5' THEN ColL
WHEN ColJ = '5' THEN ColK
WHEN ColI = '5' THEN ColJ
WHEN ColH = '5' THEN ColI
WHEN ColG = '5' THEN ColH
WHEN ColF = '5' THEN ColG
WHEN ColE = '5' THEN ColF
WHEN ColD = '5' THEN ColE
WHEN ColC = '5' THEN ColD
WHEN ColB = '5' THEN ColC
WHEN ColA = '5' THEN ColB
END AS latest
FROM table_name
<强> Results 强>:
| LATEST |
|--------|
| X6 |
答案 1 :(得分:0)
如果列名是动态的,则可以通过在订单中动态选择所需列来使用PL / SQL块。请注意,我在这里使用ROWNUM < 2
将行限制为1.如果表中有多行,则需要使用另一个循环。
SET SERVEROUTPUT ON;
DECLARE
v_col_value VARCHAR2 (10) := NULL;
v_prev_value VARCHAR2 (10) := NULL;
BEGIN
FOR cur IN ( SELECT COLUMN_NAME
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME = 'TST_TAB'
ORDER BY COLUMN_NAME DESC)
LOOP
v_prev_value := v_col_value;
EXECUTE IMMEDIATE
'SELECT ' || cur.column_name || ' FROM TST_TAB WHERE ROWNUM < 2'
INTO v_col_value;
IF v_col_value = '5'
THEN
DBMS_OUTPUT.PUT_LINE (v_prev_value);
EXIT;
END IF;
END LOOP;
END;