如何使用子查询方法来执行程序

时间:2017-03-17 15:48:28

标签: sql teradata

  SELECT SKU,  SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=6 AND  STYPE='P'
           THEN AMT 
           END) AS VALUEJUNE,
       SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=7 AND  STYPE='P'
           THEN AMT 
           END) AS VALUEJULY,
       SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=8 AND  STYPE='P'
           THEN AMT 
           END) AS VALUEAUGUST

 ,(VALUEJUNE+VALUEJULY+VALUEAUGUST) AS totalsales
FROM TRNSACT

GROUP BY SKU
ORDER BY totalsales DESC ;

1 个答案:

答案 0 :(得分:0)

将大部分查询放在派生表中,包括GROUP BY。计算结果的总数:

select sku, VALUEJUNE, VALUEJULY, VALUEAUGUST, (VALUEJUNE+VALUEJULY+VALUEAUGUST) AS totalsales
from
(
    SELECT SKU,
       SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=6 AND  STYPE='P'
           THEN AMT 
           END) AS VALUEJUNE,
       SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=7 AND  STYPE='P'
           THEN AMT 
           END) AS VALUEJULY,
       SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=8 AND  STYPE='P'
           THEN AMT 
           END) AS VALUEAUGUST
    FROM TRNSACT
    GROUP BY SKU
) dt
ORDER BY totalsales DESC ;