[英]Sql query join average of one column where another column is between two columns values of another table
[英]How to get difference between two average values in PostgreSQL, where the averages are on a column, and the final table grouped by two columns?
我想知道兩個平均值之間的差異value
,其中每個平均值都按條件isCool
過濾為True
或False
,最終結果按town
和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
category | diff :------- | ---------------------: TownB | 0.5000000000000000 TownA | 2.00000000000000000000 winter | 3.0000000000000000 spring | 3.0000000000000000
在這里, Union All
將為您提供幫助。 簡單地通過對town
進行分組然后通過對season
進行分組並合並它們來計算一次平均值的差異。 您可以像下面這樣編寫查詢:
select
town "Category",
round(abs(avg(value) filter (where iscool='t') - avg(value) filter (where iscool='f')),2) "difference_of_is_cool_averages"
from town
group by town
union all
select
season,
round(abs(avg(value) filter (where iscool='t') - avg(value) filter (where iscool='f')),2)
from town
group by season
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.