2013-10-31 65 views
0

排序順序我有在具有鍵值對存儲如下與組Oracle查詢通過並相對於密鑰

KEY  VALUE  SortOrder REGN NO 
--------------------------------------- 
KEY1 VALUE1  1   123 
KEY2 VALUE2  2   123 
KEY1 VALUE3  3   123 
KEY1 VALUE4  1   456 
KEY1 VALUE5  3   456 
KEY1 VALUE6  2   456 
KEY2 VALUE7  1   678 
KEY2 VALUE8  3   678 
Key 2 VALUE9  2   678 

對於每個鍵我已排序順序針對REGN NO Oracle數據庫值。每個REGN NO允許最多三個條目 ,但它可以是任何鍵。我需要通過將特定鍵的REGN NO分組來獲得結果,並且應該按排序順序排序。對於如對於KEY1結果看起來像

REG NO OPTION1  OPTION 2 OPTION 3 
------------------------------------------ 
123  VALUE 1  VALUE 3 
456  VALUE 4  VALUE 6  VALUE 5 

我怎樣才能獲取該使用Oracle的SQL語句?

回答

0

試試這個:

CREATE TABLE key_value (
    KEY VARCHAR2(20), 
    VALUE VARCHAR2(20), 
    SortOrder NUMBER, 
    REGN_NO NUMBER 
); 

INSERT INTO key_value VALUES ('KEY1', 'VALUE1', 1, 123); 
INSERT INTO key_value VALUES ('KEY2', 'VALUE2', 2, 123); 
INSERT INTO key_value VALUES ('KEY1', 'VALUE3', 3, 123); 
INSERT INTO key_value VALUES ('KEY1', 'VALUE4', 1, 456); 
INSERT INTO key_value VALUES ('KEY1', 'VALUE5', 3, 456); 
INSERT INTO key_value VALUES ('KEY1', 'VALUE6', 2, 456); 
INSERT INTO key_value VALUES ('KEY2', 'VALUE7', 1, 678); 
INSERT INTO key_value VALUES ('KEY2', 'VALUE8', 3, 678); 
INSERT INTO key_value VALUES ('KEY2', 'VALUE9', 2, 678); 

SELECT key, regn_no, option1, option2, option3 
    FROM (
    SELECT 
     key, 
     regn_no, 
     sortorder, 
     value AS option1, 
     LEAD(value, 1) OVER (PARTITION BY key, regn_no ORDER BY sortorder) AS option2, 
     LEAD(value, 2) OVER (PARTITION BY key, regn_no ORDER BY sortorder) AS option3 
     FROM key_value 
) kv 
WHERE 
    sortorder = (SELECT MIN(sortorder) FROM key_value WHERE key = kv.key AND regn_no = kv.regn_no) 
; 

輸出:

KEY  REGN_NO OPTION1  OPTION2  OPTION3  
------ ---------- ----------- ------------ ------------- 
KEY1   123 VALUE1  VALUE3      
KEY1   456 VALUE4  VALUE6  VALUE5  
KEY2   123 VALUE2         
KEY2   678 VALUE7  VALUE9  VALUE8 
+0

我用你的DML和DDL IN的SQL Server基本得到相同的輸出我的第二個查詢。感謝dml – realnumber3012

+0

感謝它爲我工作 –

0

RY這個解決方案)

SELECT REGNO, KEY, MAX(CASE WHEN SortOrder = 1 THEN VALUE ELSE '' END) AS OPTION1, 
    MAX(CASE WHEN SortOrder = 2 THEN VALUE ELSE '' END) AS OPTION2, 
    MAX(CASE WHEN SortOrder = 3 THEN VALUE ELSE '' END) AS OPTION3 
    FROM SomeTable 
    GROUP BY REGNO, KEY 




    SELECT REGNO, KEY, MAX(CASE WHEN num= 1 THEN VALUE ELSE '' END) AS OPTION1, 
      MAX(CASE WHEN num= 2 THEN VALUE ELSE '' END) AS OPTION2, 
      MAX(CASE WHEN num= 3 THEN VALUE ELSE '' END) AS OPTION3 
    FROM 
    (
    SELECT ROW_NUMBER() OVER(PARTITION BY REGNO, KEY ORDER BY SortOrder) AS num, * FROM SomeTable 
    ) T GROUP BY REGNO, KEY