我需要为每个组取前N行,按自定义列排序。
已知下表:
db=# SELECT * FROM xxx;
id | section_id | name
----+------------+------
1 | 1 | A
2 | 1 | B
3 | 1 | C
4 | 1 | D
5 | 2 | E
6 | 2 | F
7 | 3 | G
8 | 2 | H
(8 rows)
我需要前2行(按名称排序)为每个section_id,即类似的结果:
id | section_id | name
----+------------+------
1 | 1 | A
2 | 1 | B
5 | 2 | E
6 | 2 | F
7 | 3 | G
(5 rows)
我使用的是PostgreSQL 8.3.5。
SELECT x.*
FROM (
SELECT section_id,
COALESCE
(
(
SELECT xi
FROM xxx xi
WHERE xi.section_id = xo.section_id
ORDER BY
name, id
OFFSET 1 LIMIT 1
),
(
SELECT xi
FROM xxx xi
WHERE xi.section_id = xo.section_id
ORDER BY
name DESC, id DESC
LIMIT 1
)
) AS mlast
FROM (
SELECT DISTINCT section_id
FROM xxx
) xo
) xoo
JOIN xxx x
ON x.section_id = xoo.section_id
AND (x.name, x.id) <= ((mlast).name, (mlast).id)
SELECT x.*
FROM (
SELECT section_id,
COALESCE
(
(
SELECT xi
FROM xxx xi
WHERE xi.section_id = xo.section_id
ORDER BY
name, id
OFFSET 1 LIMIT 1
),
(
SELECT xi
FROM xxx xi
WHERE xi.section_id = xo.section_id
ORDER BY
name DESC, id DESC
LIMIT 1
)
) AS mlast
FROM (
SELECT DISTINCT section_id
FROM xxx
) xo
) xoo
JOIN xxx x
ON x.section_id = xoo.section_id
AND (x.name, x.id) <= ((mlast).name, (mlast).id)