oracle sum列作为现有表中的新列

时间:2017-09-12 09:43:16

标签: sql oracle oracle11g

我在Oracle db中有以下查询:

select 1 AS NOT_OK,
CASE WHEN
    PPLP_NAME='PPL_CH_INVOICE' THEN
    CASE WHEN 
    ( to_char(START_TIME, 'dd')<='06' and to_char(START_TIME, 'dd')=to_char(END_TIME, 'dd') )
    THEN 1 ELSE 0 END
ELSE
    CASE WHEN
    ( to_char(START_TIME, 'dd')='01' and to_char(END_TIME, 'dd')='01' ) 
    THEN 1 ELSE 0 END
END
AS STATUS, 
PPLP_NAME,SUCCESSFUL_ROWS,START_TIME,END_TIME from GENERAL_STATISTICS.PPLP_LOAD_GENSTAT2

例如,这个输出:

           NOT_OK STATUS PPLP_NAME SUCCESSFUL_ROWS START_TIME       END_TIME
                1   0   PPL_INVOICE 11598133    27/3/2013 12:34:59 PM   27/3/2013 1:23:07  PM
                1   0   PPL_INVOICE 4883282     29/3/2013 11:14:10 AM   29/3/2013 11:35:53 AM
                1   1   PPL_INVOICE 16634203    1/4/2013  5:32:28  AM   1/4/2013  6:15:21  AM
                1   0   PPL_INVOICE 16659489    26/4/2013 9:22:38  AM   26/4/2013 10:25:28 AM
                1   0   PPL_INVOICE 18192538    26/4/2013 11:02:47 AM   26/4/2013 11:54:43 AM
                1   0   PPL_INVOICE 15900000    26/4/2013 1:12:59  PM   26/4/2013 2:12:21  PM
                1   1   PPL_INVOICE 16168904    1/5/2013  12:51:37 PM   1/5/2013 2:22:21   PM
                1   1   PPL_INVOICE 16414332    1/6/2013  3:37:04  AM   1/6/2013 4:18:38   AM
                1   1   PPL_INVOICE 16112065    1/7/2013  8:17:55  AM   1/7/2013 9:38:15   AM
                1   1   PPL_INVOICE 17731276    1/8/2013  3:50:51  AM   1/8/2013 4:41:09   AM
                1   0   PPL_INVOICE 17731276    31/8/2013 3:59:38  AM   31/8/2013 4:50:42  AM
                1   1   PPL_INVOICE 17572735    1/9/2013  2:59:29  PM   1/9/2013 3:46:47   PM
                1   1   PPL_INVOICE 17820708    1/10/2013 8:36:01  AM   1/10/2013 10:16:01 AM
                1   1   PPL_INVOICE 17008019    1/11/2013 3:59:32  AM   1/11/2013 4:54:17  AM
                1   1   PPL_INVOICE 17070125    1/12/2013 4:04:20  AM   1/12/2013 4:52:03  AM

如何在上面的select语句中创建两个额外的列,一个作为状态的总和,另一个作为not_ok的总和?

提前感谢!

1 个答案:

答案 0 :(得分:1)

据我所知,我认为你可以试试:

SELECT B.* 
, SUM(B.NOT_OK) OVER (PARTITION BY TO_CHAR(START_TIME,'MM') ) AS TOT_NOT_OK
, SUM(B.STATUS) OVER (PARTITION BY TO_CHAR(START_TIME,'MM')) AS TOT_STATUS
FROM (
    SELECT 1 AS NOT_OK,
        CASE WHEN PPLP_NAME='PPL_CH_INVOICE' THEN
             CASE WHEN (to_char(START_TIME, 'dd')<='06' and to_char(START_TIME, 'dd')=to_char(END_TIME, 'dd') )
                  THEN 1 
                  ELSE 0 END
        ELSE CASE WHEN ( to_char(START_TIME, 'dd')='01' and to_char(END_TIME, 'dd')='01' ) 
                  THEN 1 
                  ELSE 0 END
        END
        AS STATUS, 
        PPLP_NAME,
        SUCCESSFUL_ROWS,
        START_TIME,END_TIME 
    FROM GENERAL_STATISTICS.PPLP_LOAD_GENSTAT2
    ) B