在Oracle PL / SQL中根据列名应用聚合函数

时间:2013-11-28 08:49:55

标签: sql oracle plsql

我有一个表test3,其中包含以下数据。我想根据状态应用聚合函数。

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

我需要输出列:

  • 请求
  • a_sum_mkt_val
  • a_avg_fill_qty
  • a_min_rate
  • r_sum_mkt_val
  • r_avg_fill_qty
  • r_min_rate
  • c_cnt(请求使用不同的c_party)
  • total_req(请求的记录总数)

前缀a_表示接受,r_表示拒绝。对于样本数据,输出应为:

IBM  900  20  1  1100  45  4  2  5

我无法根据状态对值进行分类。

1 个答案:

答案 0 :(得分:3)

SQL Fiddle

Oracle 11g R2架构设置

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;

查询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 |