不同行的排名
Rank for distincted rows
我有这个。
ID
ITEM_ID
ORDER
10
1
1
11
1
2
12
1
3
13
4
4
15
2
5
16
2
6
17
3
7
18
3
8
我需要 select 对此。为与众不同的人下订单 item_id
如果您只想按每个 item_id
的最小值 ORDER
订购,那么:
SELECT item_id,
ROW_NUMBER() OVER (ORDER BY MIN("ORDER")) AS "ORDER"
FROM table_name
GROUP BY item_id
其中,对于示例数据:
CREATE TABLE table_name (ID, ITEM_ID, "ORDER") AS
SELECT 10, 1, 1 FROM DUAL UNION ALL
SELECT 11, 1, 2 FROM DUAL UNION ALL
SELECT 12, 1, 3 FROM DUAL UNION ALL
SELECT 13, 4, 4 FROM DUAL UNION ALL
SELECT 15, 2, 5 FROM DUAL UNION ALL
SELECT 16, 2, 6 FROM DUAL UNION ALL
SELECT 17, 3, 7 FROM DUAL UNION ALL
SELECT 18, 3, 8 FROM DUAL;
注意:ORDER
是保留字,不能作为不带引号的标识符;最好使用不同的标识符而不是 ORDER
.
输出:
ITEM_ID
ORDER
1
1
4
2
2
3
3
4
如果您希望 item_id
在两次出现之间有不同的 item_id
出现多次,那么从 Oracle 12 开始,您可以使用 MATCH_RECOGNIZE
:
SELECT *
FROM table_name
MATCH_RECOGNIZE(
ORDER BY "ORDER"
MEASURES
FIRST(item_id) AS item_id,
MATCH_NUMBER() AS "ORDER"
PATTERN (same_item+)
DEFINE same_item AS FIRST(item_id) = item_id
)
上面的示例数据给出了相同的输出;但是,如果您添加一些额外的行:
INSERT INTO table_name (id, item_id, "ORDER")
SELECT 19, 1, 9 FROM DUAL UNION ALL
SELECT 20, 2, 10 FROM DUAL UNION ALL
SELECT 21, 2, 11 FROM DUAL UNION ALL
SELECT 22, 4, 12 FROM DUAL;
那么 MATCH_RECOGNIZE
查询的输出是:
ITEM_ID
ORDER
1
1
4
2
2
3
3
4
1
5
2
6
4
7
db<>fiddle here
我有这个。
ID | ITEM_ID | ORDER |
---|---|---|
10 | 1 | 1 |
11 | 1 | 2 |
12 | 1 | 3 |
13 | 4 | 4 |
15 | 2 | 5 |
16 | 2 | 6 |
17 | 3 | 7 |
18 | 3 | 8 |
我需要 select 对此。为与众不同的人下订单 item_id
如果您只想按每个 item_id
的最小值 ORDER
订购,那么:
SELECT item_id,
ROW_NUMBER() OVER (ORDER BY MIN("ORDER")) AS "ORDER"
FROM table_name
GROUP BY item_id
其中,对于示例数据:
CREATE TABLE table_name (ID, ITEM_ID, "ORDER") AS
SELECT 10, 1, 1 FROM DUAL UNION ALL
SELECT 11, 1, 2 FROM DUAL UNION ALL
SELECT 12, 1, 3 FROM DUAL UNION ALL
SELECT 13, 4, 4 FROM DUAL UNION ALL
SELECT 15, 2, 5 FROM DUAL UNION ALL
SELECT 16, 2, 6 FROM DUAL UNION ALL
SELECT 17, 3, 7 FROM DUAL UNION ALL
SELECT 18, 3, 8 FROM DUAL;
注意:ORDER
是保留字,不能作为不带引号的标识符;最好使用不同的标识符而不是 ORDER
.
输出:
ITEM_ID ORDER 1 1 4 2 2 3 3 4
如果您希望 item_id
在两次出现之间有不同的 item_id
出现多次,那么从 Oracle 12 开始,您可以使用 MATCH_RECOGNIZE
:
SELECT *
FROM table_name
MATCH_RECOGNIZE(
ORDER BY "ORDER"
MEASURES
FIRST(item_id) AS item_id,
MATCH_NUMBER() AS "ORDER"
PATTERN (same_item+)
DEFINE same_item AS FIRST(item_id) = item_id
)
上面的示例数据给出了相同的输出;但是,如果您添加一些额外的行:
INSERT INTO table_name (id, item_id, "ORDER")
SELECT 19, 1, 9 FROM DUAL UNION ALL
SELECT 20, 2, 10 FROM DUAL UNION ALL
SELECT 21, 2, 11 FROM DUAL UNION ALL
SELECT 22, 4, 12 FROM DUAL;
那么 MATCH_RECOGNIZE
查询的输出是:
ITEM_ID ORDER 1 1 4 2 2 3 3 4 1 5 2 6 4 7
db<>fiddle here