[英]SQL query to extract field values from rows sharing same value in specific column, and combine those value into a single row
[英]SQL Extract value of specific cells from GROUPed rows by condition of another column of the same row
初始表:
ROW TEAM BUDGET DATE
1 A 50 2021-01-17
2 A 100 2021-01-24
3 A 140 2021-01-31
4 A 250 2021-02-07
5 A 480 2021-03-08
6 B 70 2021-03-15
7 B 90 2021-03-16
8 B 130 2021-04-08
9 B 340 2021-05-17
10 B 680 2021-06-26
我需要:
- 了解每個團隊花費了多少預算(SUM)
- 每個團隊的第一個時間段的預算
- 每個團隊最后一個時間段的預算
我做的第一件事——按團隊摸索統計數據
ROW TEAM BUDGET_TOTAL
1 A 1020
2 B 1310
但是,我不知道要使用什么來獲取每個團隊的第一期和最后一期的預算值並將它們添加到表中,因此結果如下:
ROW TEAM BUDGET_TOTAL INITIAL_BUDJET LAST_MONTH_BUDGET
1 A 1020 50 480
2 B 1310 70 680
嘗試以下方法
select team,
sum(monthly_budget) budget_total,
array_agg(initial_monthly_budget order by month limit 1)[offset(0)] initial_budget,
array_agg(monthly_budget order by month desc limit 1)[offset(0)] last_month_budget
from (
select team, date_trunc(date, month) month,
array_agg(budget order by date limit 1)[offset(0)] initial_monthly_budget,
sum(budget) monthly_budget
from `project.dataset.table`
group by team, month
)
group by team
是否適用於您問題中的樣本數據
with `project.dataset.table` as (
select 'A' team, 50 budget, date '2021-01-17' date union all
select 'A', 100, '2021-01-24' union all
select 'A', 140, '2021-01-31' union all
select 'A', 250, '2021-02-07' union all
select 'A', 480, '2021-03-08' union all
select 'B', 70, '2021-03-15' union all
select 'B', 90, '2021-03-16' union all
select 'B', 130, '2021-04-08' union all
select 'B', 340, '2021-05-17' union all
select 'B', 680, '2021-06-26'
)
output 是
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.