假设您有一系列人们对他们喜欢的颜色的反应。此信息存储在SQL表中:
| id | favorite_color | friend_recommendation_id |
|----|----------------|--------------------------|
| 1 | green | |
| 2 | blue | |
| 3 | yellow | |
| 4 | green | |
| 5 | yellow | |
| 6 | green | |
我的目标是编写一个Postgres SQL查询,该查询会在friend_recommendation
列中填充最新人员的ID,以使用与提供的个人相同的颜色进行回复。这将产生下表:
| id | favorite_color | friend_recommendation_id |
|----|----------------|--------------------------|
| 1 | green | |
| 2 | blue | |
| 3 | yellow | |
| 4 | green | 1 |
| 5 | yellow | 3 |
| 6 | green | 4 |
请注意,身份6
已填充4
而不是1
我尝试过使用变量和子选择,但我们正在努力解决如何从父查询中应用每个结果的选择。
答案 0 :(得分:0)
使用子查询来计算字段
<强> SQL Fiddle Demo 强>
SELECT "id", "favorite_color", (SELECT MAX("id")
FROM colors c2
WHERE c2."favorite_color" = c1."favorite_color"
AND c2."id" < c1."id"
) as friend_recommendation_id
FROM colors c1
<强>输出强>
| id | favorite_color | friend_recommendation_id |
|----|----------------|--------------------------|
| 1 | green | (null) |
| 2 | blue | (null) |
| 3 | yellow | (null) |
| 4 | green | 1 |
| 5 | yellow | 3 |
| 6 | green | 4 |
也可以这样写:
SELECT c1."id", c1."favorite_color", MAX(c2."id") as friend_recommendation_id
FROM colors c1
LEFT JOIN colors c2
ON c2."favorite_color" = c1."favorite_color"
AND c2."id" < c1."id"
GROUP BY c1."id", c1."favorite_color"
ORDER BY c1."id";
<强>更新强>
UPDATE colors target
SET "friend_recomendation_id" = ( SELECT MAX("id")
FROM colors c2
WHERE c2."favorite_color" = target."favorite_color"
AND c2."id" < target."id")