简体   繁体   中英

Oracle SQL Conditional aggregate function in group by query

I'm trying to write a query that will aggregate data in a table according to a user-supplied table that drives the aggregations. I got it to work fine when I just used a sum statement, but when I put the sum inside of a case statement to allow the user to specify sum, count, mean, etc., I get group by errors.

I replaced:

 sum(column) 

with:

 CASE b.calculationtype
      WHEN 'SUM'                  THEN SUM(column)
      WHEN 'MEAN'                 THEN AVG(column)
      WHEN 'COUNT'                THEN COUNT(column)
      WHEN 'VARIANCE'             THEN VARIANCE(column)
      WHEN 'STANDARD DEVIATION'   THEN STDDEV(column)
 END

Does Oracle see beyond the case statement when evaluating the group by function or am I out of luck trying to make the actual aggregation function change based on the value in table b?

I could always brute force it the long way and move the calculationtype logic outside of the actual query, but that seems a little painful in that I'd have 5 identical queries with different aggregate functions that are called depending on the calculation type field.

   select b.REPORT,
          case b.AGG_VARIABLE_A_FLAG
           when 'N' then null
           when 'Y' then a.AGG_VARIABLE_A
          end,
          case b.AGG_VARIABLE_B_FLAG
           when 'N' then null
           when 'Y' then a.AGG_VARIABLE_B
          end,

          --<<< problem starts >>>

          case b.CALCULATIONTYPE
           when 'SUM' then sum(a.column1)  when 'MEAN' then avg(a.column1)  when 'COUNT' then count(a.column1)  when 'VARIANCE' then variance(a.column1)  when 'STANDARD DEVIATION' then stddev(a.column1)
          end,
          case b.CALCULATIONTYPE
           when 'SUM' then sum(a.column2)  when 'MEAN' then avg(a.column2)  when 'COUNT' then count(a.column2)  when 'VARIANCE' then variance(a.column2)  when 'STANDARD DEVIATION' then stddev(a.column2)
          end

          --<<< problem ends >>

     from DATA_TABLE a
             cross join CONTROL_TABLE b
    where a.ID = bind_variable_id
          and a.SOURCEARRAY = b.SOURCEARRAY
          and b.CALCULATIONTYPE <> 'INTERNAL'
    group by b.REPORT,
          case b.AGG_VARIABLE_A_FLAG
           when 'N' then null
           when 'Y' then a.AGG_VARIABLE_A
          end,
          case b.AGG_VARIABLE_B_FLAG
           when 'N' then null
           when 'Y' then a.AGG_VARIABLE_B
          end

GROUP BY子句中添加b.calculationtype

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