SQLite:由两列索引的列的平均值

时间:2018-09-08 15:49:17

标签: sql sqlite

给出下表

+----+----+------+
|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

我们将不胜感激。

1 个答案:

答案 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;

DBFidde Demo