在Teradata SQL中添加总计百分比的列

时间:2017-09-26 16:08:30

标签: sql teradata percentage

我正在尝试找出一种方法来根据列的信息添加具有总计百分比的列。我认为这是可能的,但我无法掌握这样做的方法。

这是我的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

我想做的是为该周的餐饮和餐厅创造两个额外的列,即每餐时间收入的百分比。

因此,例如,第一周的炸玉米饼铃将含有早餐食物的百分比为.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

1 个答案:

答案 0 :(得分:1)

您可以使用团体总和来获得每周/餐厅的总和,如下所示:

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