【发布时间】:2020-12-30 12:12:14
【问题描述】:
我在 Postgresql 中有这个查询:
(SELECT q.question, q.category_id, a.id, a.question_id, a.answer
FROM questions q, answers a
WHERE q.id = a.question_id
AND category_id = 1
AND question_id
BETWEEN (SELECT property FROM users WHERE email = 'test@test.com')
AND (SELECT property FROM users WHERE email = 'test@test.com') + 14)
UNION
(SELECT q.question, q.category_id, a.id, a.question_id, a.answer
FROM questions q, answers a
WHERE q.id = a.question_id
AND category_id = 2
AND question_id
BETWEEN (SELECT laws FROM users WHERE email = 'test@test.com')
AND (SELECT laws FROM users WHERE email = 'test@test.com') + 16)
ORDER BY question_id, id
当前以这种格式返回结果:
+-----------------------------+-------------+-------------+--------+
| question | category_id | question_id | answer |
+-----------------------------+-------------+-------------+--------+
| What color is the sky? | 1 | 16 | blue |
| What color is the sky? | 1 | 16 | green |
| What color is the sky? | 1 | 16 | purple |
| What color is the sky? | 1 | 16 | red |
| What color is a firetruck? | 1 | 17 | orange |
| What color is a firetruck? | 1 | 17 | teal |
| What color is a firetruck? | 1 | 17 | red |
| What color is a firetruck? | 1 | 17 | green |
| What color is dirt? | 2 | 18 | green |
| What color is dirt? | 2 | 18 | green |
| What color is dirt? | 2 | 18 | green |
| What color is dirt? | 2 | 18 | green |
+-----------------------------+-------------+-------------+--------+
我想要做的是根据 category_id 交替顺序,因此类别 id 将像这样交替:1、2、1、2,但我想根据 question_id 保留组。所以结果应该是这样的:
+-----------------------------+-------------+-------------+--------+
| question | category_id | question_id | answer |
+-----------------------------+-------------+-------------+--------+
| What color is the sky? | 1 | 16 | blue |
| What color is the sky? | 1 | 16 | green |
| What color is the sky? | 1 | 16 | purple |
| What color is the sky? | 1 | 16 | red |
| What color is dirt? | 2 | 18 | green |
| What color is dirt? | 2 | 18 | green |
| What color is dirt? | 2 | 18 | green |
| What color is dirt? | 2 | 18 | green |
| What color is a firetruck? | 1 | 17 | orange |
| What color is a firetruck? | 1 | 17 | teal |
| What color is a firetruck? | 1 | 17 | red |
| What color is a firetruck? | 1 | 17 | green |
+-----------------------------+-------------+-------------+--------+
我尝试过使用ORDER BY row_number() OVER (PARTITION BY t.category_id ORDER BY t.category_id)
但这只会导致每个都被交替而不被 question_id 分组
【问题讨论】:
标签: sql postgresql sql-order-by union window-functions