我有像
这样的列periodbal balancetype
------------- -------------
0;15;11;-13;-16;20 ABS
22;25;-78;0;1 ABS
67;89;-36;83;90;55 ABS
… ACS
…
我想要检索
periodbal balancetype
--------- -------------
20 ABS
25 ABS
90 ABS
答案 0 :(得分:3)
这里的想法是:
对于balancetype的每个值,从periodbal列中提取所有值,将它们转换为单独的行,然后计算每行的平衡类型值的最大值。
即。
PERIODBAL BALANCETYPE ID
0 ABS 1
15 ABS 1
11 ABS 1
-13 ABS 1
-16 ABS 1
20 ABS 1
SPLIT FOR ROW#2
22 ABS 2
25 ABS 2
-78 ABS 2
0 ABS 2
1 ABS 2
......
最后,FETCH MAX(PERIODBAL)并按列balancetype,ID
对数据进行分组CREATE TABLE SYS.TEST
(
PERIODBAL VARCHAR2(50 BYTE),
BALANCETYPE VARCHAR2(5 BYTE)
)
INSERT INTO TEST VALUES ('0;15;11;-13;-16;20', 'ABS');
INSERT INTO TEST VALUES ('22;25;-78;0;1', 'ABS');
INSERT INTO TEST VALUES ('67;89;-36;83;90;55 ', 'ABS');
INSERT INTO TEST VALUES ('0;15;10;-13;-16;23', 'ACS');
INSERT INTO TEST VALUES ('0;14;11;-13;-16;25', 'ACS');
溶液:
SELECT BALANCETYPE,MAX(BAL) AS PERIODBAL
FROM
(
SELECT SUB1.*, TRIM(REGEXP_SUBSTR( PERIODBAL, '[^;]+', 1, LVL)) BAL
FROM (SELECT TEST.*, ROW_NUMBER() OVER (ORDER BY BALANCETYPE ) UNIQ_ID FROM TEST) SUB1 ,
(SELECT LEVEL LVL FROM DUAL,(SELECT MAX(LENGTH(REGEXP_REPLACE(PERIODBAL, '[^;]+')))+1 AS MAX_BAL FROM TEST) TEMP
CONNECT BY LEVEL<= TEMP.MAX_BAL ) SUB2
WHERE LENGTH(REGEXP_REPLACE(PERIODBAL, '[^;]+'))+1>= SUB2.LVL
) GROUP BY BALANCETYPE, UNIQ_ID
输出:
BALANCETYPE PERIODBAL
ACS 23
ABS 20
ABS 25
ABS 90
ACS 25
希望它有所帮助,谢谢。
答案 1 :(得分:0)
在 MySQL 中,您可以尝试
SELECT balanceType, MAX(CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(t.periodBal, ';', n.n), ';', -1), SIGNED INTEGER)) maxValue
FROM SomeData t CROSS JOIN
(
SELECT a.N + b.N * 10 + 1 n
FROM
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
ORDER BY n
) n
WHERE n.n <= 1 + (LENGTH(t.periodBal) - LENGTH(REPLACE(t.periodBal, ';', '')))
GROUP BY periodBal, balanceType
ORDER BY periodBal, maxValue;
查看实际操作:SQL Fiddle(稍微调整数据以检查某些边框情况)。
这借鉴了SQL split comma separated row
但是,我能够找到的这种方法最早的SO参考是Creating a MySQL SET's from a string