简体   繁体   中英

Combining window functions and group by in Teradata

There is a situation where I'm counting rows per category in a query, and I want to know the percentage of rows from the main category are in the subcategories. I simplified the query to the one below (using sum instead of count, to make the example shorter), but when writing the window function I'm getting the following error:

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

I know I still have to add a division by SUM(tx), but even without it I'm getting the error. 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;

I was expecting to get the following output from this query:

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

And I would like to convert that last column to a "share per subcategory" in percentage.

OLAP functions are logically processed after aggregation, you need to apply the SUM on the aggregated data, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM