Teradata错误“选定的非聚合值必须是关联组的一部分”

时间:2017-07-21 13:13:36

标签: sql teradata

>SELECT sku, jun_sale, jul_sale, aug_sale, (jun_sale + jul_sale + aug_sale) 
>AS total_sale,
>CASE 
>when EXTRACT(MONTH from saledate)=6 AND stype= 'P'
>then sum(amt)
>end as jun_sale,
>CASE
>when EXTRACT(MONTH from saledate)=7 AND stype= 'P'
>then sum(amt)
>end as jul_sale,
>CASE
>when EXTRACT(MONTH from saledate)=8 AND stype= 'P'
>then sum(amt)
>end as aug_sale
>FROM trnsact
>group by 1
>order by total_sale;
  

选定的非聚合值必须是关联组的一部分

有人可以找出案件中的错误吗?

1 个答案:

答案 0 :(得分:0)

您可能希望SUM over CASE:

select sku,
   sum(case 
         when EXTRACT(MONTH from saledate)=6 AND stype= 'P'
         then amt
       end) as jun_sale,
   sum(case 
         when EXTRACT(MONTH from saledate)=7 AND stype= 'P'
         then amt
       end) as jul_sale,
   sum(case 
         when EXTRACT(MONTH from saledate)=8 AND stype= 'P'
         then amt
       end) as aug_sale,
   jun_sale + jul_sale + aug_sale as total_sale
from trnsact
group by 1
order by total_sale;

您应该在6月到8月之间添加限制行的WHERE条件。

编辑:

如果一个项目在三个月中没有出售,您将获得NULL(然后total_sale计算也将导致NULL)。您可以为每个CASE添加else 0以获得零。