将ratio_to_report与3个或更多分组一起使用Oracle SQL

时间:2018-09-11 21:45:31

标签: sql database oracle analytics business-intelligence

我正在尝试建立一个查询,以根据商店数量,客户群和品牌分组汇总销售总额的百分比。理想情况下,我希望得到以下结果:

 Store --------Segment-------Brand------Sales--------pct_total
    1              A            X         50            66.6
    1              A            Y         25            33.3
    1              B            X         25            25.0
    1              B            Y         25            25.0
    1              B            Z         50            50.0

这是我到目前为止与包含此数据所需的表的代码。

 select Store,Segment,Brand, to_char(100 * ratio_to_report(total_sales) over (partition by store, segment, brand),'990.00L','NLS_CURRENCY=%') as pct_total
 from ( 
         select 
           Store,
           Segment,
           Brand,
           sum(sales) as total_sales
           from customer_data 
           group by grouping sets ((Store),(store,Segment,brand)))

由于分组,这只是给我一个错误

1 个答案:

答案 0 :(得分:0)

不需要分组集,这将返回预期的结果:

select Store,Segment,Brand, total_sales,
   to_char(100 * ratio_to_report(total_sales) over (partition by store, segment),'990.00L','NLS_CURRENCY=%') as pct_total
from ( 
        select 
          Store,
          Segment,
          Brand,
          sum(sales) as total_sales
          from customer_data 
          group by store,Segment,brand)