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 的排序顺序。每个 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 语句来获取它?

4

2 回答 2

0

试试这个解决方案)

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
于 2013-10-31T00:36:24.710 回答
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      
------ ---------- ----------- ------------ ----------- --
键 1 123 值 1 值 3                    
键 1 456 值 4 值 6 值 5       
键 2 123 值 2                                
键 2 678 值 7 值 9 值 8       
于 2013-10-31T00:47:33.057 回答