我在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语句获取此信息?
答案 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
答案 1 :(得分: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