在 Teradata 中组合 window 函数和分组依据

Combining window functions and group by in Teradata

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

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

我想将最后一列转换为 "share per subcategory" 百分比。

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