首页 > 解决方案 > 如何获取 PostgreSQL 中的两个平均值之间的差异,平均值在列上,最终表按两列分组?

问题描述

我想知道 的两个平均值之间的差异value,其中每个平均值都由一个条件过滤isCoolTrueor False,最终结果由townand分组season,例如

table

| id | value | isCool | town   | season |
|----|-------|--------|--------|--------|
| 0  | 1     | True   | TownA  | spring |
| 1  | 2     | False  | TownA  | winter |
| 2  | 3     | True   | TownB  | spring |
| 3  | 4     | False  | TownA  | winter |
| 4  | 5     | False  | TownB  | spring |
| 5  | 6     | True   | TownB  | winter |

我想以表格结束:

| category | difference_of_is_cool_averages |
|----------|--------------------------------|
| TownA    | 2                              | <-- ABS(1 - (2 + 4)/2)
| TownB    | 0.5                            | <-- ABS(5 - (3 + 6)/2)
| spring   | 3                              | <-- ABS(5 - (3 + 1)/2)
| winter   | 3                              | <-- ABS(6 - (4 + 2)/2)

我已经尝试过了,但我的 PostgreSQL 技能有限,而且我没有走多远,不幸的是。我试过了

SELECT
   AVG(value), town
   (SELECT id, value, town, season
   FROM table
   WHERE isCool = 'True') AS TableSummary1
GROUP BY town;

但这远非我想要的。请问有人可以帮忙吗?PostgreSQL甚至可以做到这一点吗?

标签: sqlpostgresqlaverageunpivot

解决方案


您可以取消透视,然后计算每组的两个条件平均值之间的差异:

select x.category, 
    abs(avg(t.value) filter(where not t.iscool) - avg(t.value) filter(where t.iscool)) diff
from mytable t
cross join lateral (values (town), (season)) as x(category)
group by x.category

如果您希望能够按照所需结果对结果集进行排序,那么我们需要跟踪原始列:

select x.category, 
    abs(avg(t.value) filter(where not t.iscool) - avg(t.value) filter(where t.iscool)) diff
from mytable t
cross join lateral (values (town, 1), (season, 2)) as x(category, grp)
group by x.category, x.grp
order by x.grp

DB Fiddle 上的演示

类别 | 差异
:------- | ---------------------:
镇B | 0.5000000000000000
镇A | 2.00000000000000000000
冬天| 高分辨率照片| CLIPARTO 3.0000000000000000
弹簧 | 3.0000000000000000

推荐阅读