我有一个表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_
表示接受,r_
表示拒绝。对于样本数据,输出应为:
IBM 900 20 1 1100 45 4 2 5
我无法根据状态对值进行分类。
答案 0 :(得分:3)
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 |