2017-09-26 179 views
0

我想找出一種方法來添加一個列的總數的百分比基於列的信息。我認爲這是可能的,但我無法掌握如何去做。在Teradata SQL中添加一個總數的百分比SQL

這裏是我的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 

回答

0

可以利用團體總和,以獲得每週的總和/像這樣的餐廳:

100.00 * food_rev/sum(food_rev) over (partition by week restaurant)