在Teradata中组合窗口函数和分组

时间:2017-11-28 13:58:45

标签: sql teradata

在某种情况下,我在查询中计算每个类别的行数,我想知道主类别中行的百分比在子类别中。我将查询简化为下面的一个(使用sum而不是count,使示例更短),但在编写窗口函数时,我收到以下错误:

Failed [3504 : HY000] Selected non-aggregate values must be part of the associated group. 

我知道我仍然需要通过SUM(t.x)添加除法,但即使没有它我也会得到错误。 SQL:

select cat, subcat, sum(t.x), sum(t.x) OVER(PARTITION BY cat) as xx
from (select * from (select 5 as x, 'prod1' as cat, 'A' as subcat) x
      union all
      select * from (select 10 as x, 'prod1' as cat, 'B' as subcat) x
      union all
      select * from (select 11 as x, 'prod1' as cat, 'C' as subcat) x
      union all
      select * from (select 3 as x, 'prod2' as cat, 'A' as subcat) x
      union all
      select * from (select 6 as x, 'prod2' as cat, 'B' as subcat) x
     ) t
GROUP BY cat, subcat
ORDER BY cat, subcat;

我希望从此查询中获得以下输出:

prod1, A, 5,  26
prod1, B, 10, 26
prod1, C, 11, 26
prod2, A, 3,  9
prod2, B, 6,  9

我想将最后一列转换为"每个子类别的份额"百分比。

1 个答案:

答案 0 :(得分:2)

OLAP功能在聚合后以逻辑方式处理,您需要在聚合数据上应用SUM,例如

select cat, subcat, 
   sum(t.x), 
   100 * sum(t.x) / sum(sum(t.x)) OVER(PARTITION BY cat) as xx
from ...
GROUP BY cat, subcat