我在 PostgreSQL 資料庫中有以下格式的資料:
unique_key category date_period value
所以例如。
agriculture_all agriculture 2021 15
agriculture_partial agriculture 2021 10
science_all science 2021 83
science_partial science 2021 32
我想運行的查詢是GROUP BY基于categoryand date_period,然后顯示彼此相鄰的值。
**[query here]**
output:
category date_period all partial
agriculture 2021 15 10
science 2021 83 32
這感覺就像一個非常簡單的請求,但我正在努力讓它在 SQL 中正常作業。任何建議表示贊賞。
uj5u.com熱心網友回復:
在 PostgreSQL 中,您可以使用sumwith使用簡單查詢filter:
select
category,
sum(value) filter (where unique_key like '%_all') all,
sum(value) filter (where unique_key like '%_partial') partial
from tbl
group by category;
PostgreSQL 總和過濾器小提琴
對于防止null值coalesce函式可以應用:
select
category,
coalesce(sum(value) filter (where unique_key like '%_all'), 0) all,
coalesce(sum(value) filter (where unique_key like '%_partial'), 0) partial
from tbl
group by category;
PostgreSQL 合并過濾器
uj5u.com熱心網友回復:
您可以使用公用表運算式...
with partial as
(select category, date_period, value
from t1
where unique_key ilike '%partial%'
)
select a.category,
a.date_period,
a.value as all,
coalesce(p.value, 0) as partial
from t1 a
left join partial p
on p.category = a.category
and p.date_period = a.date_period
where a.unique_key ilike '%all%'
資料庫小提琴在這里
uj5u.com熱心網友回復:
一些條件聚合可以解決問題。
SELECT
t.category
, t.date_period
, SUM(CASE WHEN t.unique_key LIKE '%\_all' THEN t.value ELSE 0 END) AS "all"
, SUM(CASE WHEN t.unique_key LIKE '%\_partial' THEN t.value ELSE 0 END) AS "partial"
FROM your_table t
GROUP BY t.category, t.date_period
ORDER BY t.category, t.date_period
類別 | date_period | 所有 | 部分的 :---------- | ----------: | --: | ------: 農業| 2021 | 15 | 10 科學 | 2021 | 83 | 32
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360564.html
標籤:sql PostgreSQL的
