鉴于我有以下表table1
field1 field2
A B
A C
D B
D C
E F
G F
我正在尝试获取一个查询来分区我的数据并对每个分区中的成员进行排名。我希望我的查询看起来像下面的那个,但我不确定如何实现field1 OR field2
条件:
SELECT
field1, field2, ???? as partition,
RANK() OVER ( PARTITION BY field1 OR field2) as rank
FROM table1
field1 field2 partition rank
A B 1 1
A C 1 2
D B 1 3
D C 1 4
E F 2 1
G F 2 2
答案 0 :(得分:2)
这真的不是一个简单/好的解决方案,但这样做:
Oracle安装程序:
CREATE TABLE table_name (
field1 VARCHAR2(10),
field2 VARCHAR2(10)
);
INSERT INTO table_name
SELECT 'A', 'B' FROM DUAL UNION ALL
SELECT 'A', 'C' FROM DUAL UNION ALL
SELECT 'D', 'B' FROM DUAL UNION ALL
SELECT 'D', 'C' FROM DUAL UNION ALL
SELECT 'E', 'F' FROM DUAL UNION ALL
SELECT 'G', 'F' FROM DUAL;
CREATE OR REPLACE TYPE StringList AS TABLE OF VARCHAR2(50);
/
<强>查询强>:
SELECT field1,
field2,
"partition",
ROW_NUMBER() OVER ( PARTITION BY "partition" ORDER BY field1, field2 )
AS "rank"
FROM (
SELECT field1,
f.COLUMN_VALUE AS field2,
DENSE_RANK() OVER ( ORDER BY partition_string ) AS "partition"
FROM (
SELECT field1,
CAST( COLLECT( field2 ORDER BY field2 ) AS StringList ) AS field2s,
LISTAGG( field2, ',' ) WITHIN GROUP ( ORDER BY field2 )
AS partition_string
FROM table_name
GROUP BY field1
) t,
TABLE( field2s ) f
);
<强>输出强>:
FIELD1 FIELD2 partition rank
------ ------ ---------- ----
A B 1 1
A C 1 2
D B 1 3
D C 1 4
E F 2 1
G F 2 2