Search code examples
sqloracle-databasestored-proceduresprocedurecreate-view

SQL Create view or procedure in a SUM query without adding new column?


Supposed I have some sample data in table_name_a as below:

    code    val    remark   date
   -----------------------------------
1   00001    500    111      20191108
2   00001   1000    222      20191107
3   00002    200    111      20191108
4   00002    400    222      20191108
5   00001    200    333      20191108
6   00001    400    444      20191108

And I have a SQL query as below:

SELECT t.code, 
       sum(CASE WHEN t.remark IN ('111', '222', '333')
       THEN t.value ELSE 0 END) AS sum_123
FROM table_name_a t
    WHERE t.code='00001' and t.date='20191108'
GROUP BY t.code

Output as below:

    code    sum_123
   ------------------
1   00001    1100        

Now I would like to create a view or procedure use above SQL query(Oracle), we don't want a new column, is it possible to let sum_123 store into remark column? Supposed if I use below SQL query

SELECT t.code, t.value
FROM table_name_a t 
    WHERE t.remark='sum_123' and t.code='00001' and t.date='20191108'
GROUP BY t.code

and if I use above SQL query, my expected output as below:

    code    val        remark          date
   ------------------------------------------
1   00001    1100    sum_123          20191108 

Is it possible to use create view/procedure save remark and val with sum_123and the value/result of 1100? Thanks so much for any advice.


Solution

  • Is this what you want?

    select t.code, 
           sum(case when t.remark IN ('111', '222', '333') then t.value else 0 end) as val,
           'sum_123' as remark,
           date
    from table_name_a t
    where t.code = '00001' and t.date = '20191108'
    group by t.code, date;