给出下表
+----+----+------+
|id1 |id2 |value |
+----+----+------+
| 1 | 2 | 10 |
| 1 | 3 | 20 |
| 1 | 4 | 30 |
| 2 | 3 | 10 |
| 2 | 4 | 40 |
| 3 | 4 | 10 |
+----+----+------+
我想让每个id的avg(value),无论位于id1还是id2列。
因此,输出应为:
1,20
2,20
3,16.66
4,26.6
我们将不胜感激。
答案 0 :(得分:3)
您可以使用UNION ALL
:
WITH cte AS (
SELECT id, value FROM tab
UNION ALL
SELECT id2, value FROM tab
)
SELECT id, AVG(value) AS value
FROM cte
GROUP BY id;