我正在尝试找出一种方法来添加基于列信息占总数百分比的列。我认为这是可能的,但我只是无法掌握做到这一点的方法。
这是我的 SQL 代码的简化版本(运行良好)和表结果:
select week
, restaurant
, case
when cast(timestamp as time format 'HH:MI:SS') between '03:00:01' and '10:00:00' then 'Breakfast'
when cast(timestamp as time format 'HH:MI:SS') between '10:00:01' and '14:59:00' then 'Lunch'
else 'Dinner'
end
as meal
, sum(revenue) as total_rev
, sum(case when product_type = 'food' then revenue else 0 end) as food_rev
, sum(case when product_type = 'bev' then revenue else 0 end) bev_rev
from table1
group by 1,2,3
order by 1,2,3
表格输出
week restaurant meal total_rev food_rev bev_rev
1 Taco Bell Breakfast 300 200 100
1 Taco Bell Lunch 250 210 40
1 Taco Bell Dinner 450 250 200
1 McDonalds Breakfast 100 70 30
1 McDonalds Lunch 150 100 50
1 McDonalds Dinner 250 130 120
2 Taco Bell Breakfast 200 120 80
2 Taco Bell Lunch 150 110 40
2 Taco Bell Dinner 350 240 110
2 McDonalds Breakfast 200 70 130
2 McDonalds Lunch 250 120 130
2 McDonalds Dinner 150 100 50
我想要做的是创建两个额外的列,分别表示该周和餐厅的食品和饮料的每餐时段的收入百分比。
例如,塔可钟第一周的早餐食物百分比为 0.3030 (200/(200 + 210 + 250)。依此类推。
week restaurant meal total_rev food_rev per_food bev_rev per_bev
1 Taco Bell Breakfast 300 200 .3030 100 .2941
1 Taco Bell Lunch 250 210 .3182 40 .1176
1 Taco Bell Dinner 450 250 .3788 200 .5882
1 McDonalds Breakfast 100 70 30
1 McDonalds Lunch 150 100 50
1 McDonalds Dinner 250 130 120
2 Taco Bell Breakfast 200 120 80
2 Taco Bell Lunch 150 110 40
2 Taco Bell Dinner 350 240 110
2 McDonalds Breakfast 200 70 130
2 McDonalds Lunch 250 120 130
2 McDonalds Dinner 150 100 50
最佳答案
您可以利用团体总和来获取每周/餐厅的总和,如下所示:
100.00 * food_rev / sum(food_rev) over (partition by week restaurant)
关于sql - 在 Teradata SQL 中添加总计百分比列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46431226/