我有一個 Postgres 表,其中包含人們的姓名、年齡和他們擁有的彈珠數量。為簡單起見,該示例只有兩行,但可能更多。
| 姓名 | 年齡 | 彈珠 |
|---|---|---|
| 愛麗絲 | 4 | 10 |
| 鮑勃 | 7 | 20 |
我想檢索每個年齡組的彈珠數量,其中彈珠的數量分配給每個年齡組,與人的年齡成正比。年齡組可以變化,但在查詢時間2是已知的。
輸出將如下所示:
| 年齡階層 | 彈珠 |
|---|---|
| 0 | 2 (愛麗絲彈珠的 1/5) |
| 5 | 20 (愛麗絲彈珠的 4/5,鮑勃彈珠的 3/5) |
| 10 | 8 (鮑勃彈珠的 2/5) |
有沒有一種優雅的方式來查詢我的表來實作這一點?
1具體來說,一個人每個年齡組的彈珠比例為:
marbles_higher_age_group = (age - lower_age_group) / (higher_age_group - lower_age_group) * marbles
marbles_lower_age_group = marbles - marbles_higher_age_group
2查詢表時,年齡組是已知的。它們可以在多個查詢中有所不同,并且可以任意選擇。例如,一個查詢可能使用年齡組[0,5,10],而下一個查詢使用[0,1,4,8,12].
uj5u.com熱心網友回復:
對于存盤在表中的任意年齡組
select ag, sum(agm) marbles
from marbles m
join (
select age_group low, lead(age_group) over(order by age_group) high
from age_groups ag
) a on a.high >= m.age and a.low <= m.age
, lateral (
select a.low ag , 1.0 * m.marbles * (a.high - m.age)/(a.high - a.low) agm
union all
select a.high, 1.0 * m.marbles * (m.age - a.low)/(a.high - a.low)
) mm
group by ag
order by ag;
或者,您可以在查詢中提供一組年齡組
select ag, sum(agm) marbles
from marbles m
join (
select age_group low, lead(age_group) over(order by age_group) high
from unnest(array[1,2,4,8,12]) age_groups(age_group)
) a on a.high >= m.age and a.low <= m.age
, lateral (
select a.low ag, 1.0 * m.marbles * (a.high - m.age)/(a.high - a.low) agm
union all
select a.high, 1.0 * m.marbles * (m.age - a.low)/(a.high - a.low)
) mm
group by ag
order by ag;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463288.html
標籤:sql 数据库 PostgreSQL
