简体   繁体   中英

Apply aggregate function based on column name in Oracle PL/SQL

I have a table test3 which has the data below. I want to apply aggregate function based on status.

request mkt_val fill_val qty fill_qty rate c_party status
------- ------- -------- --- -------- ---- ------- ------
    IBM     200      100  20       10    1   test1 Accept
    IBM     300      200  30       20    2   test1 Accept
    IBM     400      300  40       30    3   test1 Accept
    IBM     500      400  50       40    4   test2 Reject
    IBM     600      500  60       50    5   test2 Reject

I need output with the columns:

  • request
  • a_sum_mkt_val
  • a_avg_fill_qty
  • a_min_rate
  • r_sum_mkt_val
  • r_avg_fill_qty
  • r_min_rate
  • c_cnt (distinct c_party for request)
  • total_req (total number of records for request)

Prefix a_ for accept, r_ for reject. For the sample data, the output should be:

IBM  900  20  1  1100  45  4  2  5

I am not able to categorise the value based on the status.

SQL Fiddle

Oracle 11g R2 Schema Setup :

CREATE TABLE tbl ( request, mkt_val, fill_val, qty, fill_qty, rate,  c_party,  status ) AS
          SELECT 'IBM',     200,      100,  20,       10,    1,   'test1', 'Accept' FROM DUAL
UNION ALL SELECT 'IBM',     300,      200,  30,       20,    2,   'test1', 'Accept' FROM DUAL
UNION ALL SELECT 'IBM',     400,      300,  40,       30,    3,   'test1', 'Accept' FROM DUAL
UNION ALL SELECT 'IBM',     500,      400,  50,       40,    4,   'test2', 'Reject' FROM DUAL
UNION ALL SELECT 'IBM',     600,      500,  60,       50,    5,   'test2', 'Reject' FROM DUAL;

Query 1 :

SELECT request,
       SUM( DECODE( status, 'Accept', mkt_val,  NULL ) ) AS a_sum_mkt_val,
       AVG( DECODE( status, 'Accept', fill_qty, NULL ) ) AS a_avg_fill_qty,
       MIN( DECODE( status, 'Accept', rate,     NULL ) ) AS a_min_rate,
       SUM( DECODE( status, 'Reject', mkt_val,  NULL ) ) AS r_sum_mkt_val,
       AVG( DECODE( status, 'Reject', fill_qty, NULL ) ) AS r_avg_fill_qty,
       MIN( DECODE( status, 'Reject', rate,     NULL ) ) AS r_min_rate,
       COUNT( DISTINCT c_party ) AS c_cnt,
       COUNT( 1 ) AS total_req
FROM   tbl
GROUP BY request

Results :

| REQUEST | A_SUM_MKT_VAL | A_AVG_FILL_QTY | A_MIN_RATE | R_SUM_MKT_VAL | R_AVG_FILL_QTY | R_MIN_RATE | C_CNT | TOTAL_REQ |
|---------|---------------|----------------|------------|---------------|----------------|------------|-------|-----------|
|     IBM |           900 |             20 |          1 |          1100 |             45 |          4 |     2 |         5 |

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