【发布时间】:2016-11-17 10:01:58
【问题描述】:
我正在寻找有关如何在 SQLite 中选择每个组的第一条记录的选项,其中组的排序跨复合键。
示例表:
Key_1 | Sort1 | Sort2 | Val_1 | Val_2
-------+-------+-------+-------+-------
1 | 1 | 3 | 0 | 2
1 | 1 | 2 | 2 | 4
1 | 1 | 1 | 4 | 6
1 | 2 | 2 | 6 | 8
1 | 2 | 1 | 8 | 1
2 | 1 | 2 | 0 | 5
2 | 1 | 1 | 1 | 6
2 | 2 | 3 | 2 | 7
2 | 2 | 2 | 3 | 8
2 | 2 | 1 | 4 | 9
目标:
- 按Key_1 ASC, Sort1 ASC, Sort2 DESC对数据进行排序
- 选择每个唯一Key_1 的第一条记录
Key_1 | Sort1 | Sort2 | Val_1 | Val_2
-------+-------+-------+-------+-------
1 | 1 | 3 | 0 | 2
2 | 1 | 2 | 0 | 5
解析函数解...
SELECT
*
FROM
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Key_1
ORDER BY Sort1,
Sort2 DESC
)
AS group_ordinal
FROM
table
)
sorted
WHERE
group_ordinal = 1
费力的 ANSI-92 方法...
SELECT
table.*
FROM
table
INNER JOIN
(
SELECT
table.Key1, table.Sort1, MAX(table.Sort2) AS Sort2
FROM
table
INNER JOIN
(
SELECT
Key_1, MIN(Sort1)
FROM
table
GROUP BY
Key_1
)
first_Sort1
ON table.Key_1 = first_Sort1.Key_1
AND table.Sort1 = first_Sort1.Sort1
GROUP BY
table.Key1, table.Sort1
)
first_Sort1_last_Sort2
ON table.Key_1 = first_Sort1_last_Sort2.Key_1
AND table.Sort1 = first_Sort1_last_Sort2.Sort1
AND table.Sort2 = first_Sort1_last_Sort2.Sort2
这涉及到大量的嵌套和自连接。当它只涉及两个排序列时,这就够麻烦了。
我的实际示例有 六个 排序列。
我也想避免类似以下的事情,因为它不是 (据我所知)保证/确定...
SELECT
table.*
FROM
table
GROUP BY
table.Key_1
ORDER BY
MIN(table.Sort1),
MAX(table.Sort2)
还有其他我没有看到的选项吗?
【问题讨论】:
标签: sql sqlite greatest-n-per-group