sql - 如何获取 PostgreSQL 中的两个平均值之间的差异,平均值在列上,最终表按两列分组?
问题描述
我想知道 的两个平均值之间的差异value
,其中每个平均值都由一个条件过滤isCool
为True
or False
,最终结果由town
and分组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甚至可以做到这一点吗?
解决方案
您可以取消透视,然后计算每组的两个条件平均值之间的差异:
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
类别 | 差异 :------- | ---------------------: 镇B | 0.5000000000000000 镇A | 2.00000000000000000000 冬天| 高分辨率照片| CLIPARTO 3.0000000000000000 弹簧 | 3.0000000000000000
推荐阅读
- php - 通过 HTTP API 将 PHP 数组转换为 NEO4J 查询的 JSON 格式
- mql4 - 如何在 mql4 中找到之前的最后一个移动平均交叉价格 x 蜡烛?
- javascript - 在 Angular 之外管理的事件的 Angular 更改范围/区域
- kubernetes - 通过 kubernetes 的 azure websocket 连接,许多使用代码 1006 断开连接
- python - mypy 可以跟踪字符串文字吗?
- python - 解决E11000重复密钥错误收集:pymongo中的_id_ dup key
- azure - Azure 事件中心吞吐量
- javascript - 开始出现 TypeError:无法读取未定义的属性“getCapabilities”
- docker - 无法运行已在使用的 gitlab docker 映像端口
- latex - 引用电子邮件文本中的行