1

当“月份”列的值为 2 月时,我想在查询输出中添加一行。

请看示例:

SQL> select * from CUSTOMER;
CUST_ID MONTH           SPEND

     1 Jan               100
     1 Feb               200
     1 Apr                20
     2 Jan               145
     2 Mar                50
     3 May               100
     4 Feb               250

------需要输出-----

CUST_ID MONTH                          SPEND

     1 Jan                              100
     1 Feb                              200
     1 Feb-Reversal                    -200
     1 Apr                               20
     2 Jan                              145
     2 Mar                              50
     3 May                              100
     4 Feb                              250
     4 Feb-Reversal                    -250

请帮忙。

4

2 回答 2

1

尝试这个:

CREATE TABLE customer (cust_id NUMBER, month VARCHAR2(3), spend NUMBER);

INSERT INTO customer VALUES (1, 'Jan', 100);
INSERT INTO customer VALUES (1, 'Feb', 200);
INSERT INTO customer VALUES (1, 'Apr', 20);
INSERT INTO customer VALUES (2, 'Jan', 145);
INSERT INTO customer VALUES (2, 'Mar', 50);
INSERT INTO customer VALUES (3, 'May', 100);
INSERT INTO customer VALUES (4, 'Feb', 250); 

COMMIT;

SELECT cust_id, month, spend
  FROM customer
UNION ALL
SELECT cust_id, month || '-Reversal', -spend
  FROM customer
WHERE month = 'Feb'
ORDER BY 1, 2;

查看 SQLFiddle:http ://sqlfiddle.com/#!4/0ad222/1

于 2013-10-04T09:54:04.943 回答
1

像这样试试

WITH t(ID_, mon, VALUE_) as
(
SELECT 1, 'Jan', 100 FROM dual
union
SELECT 1, 'Feb',200 FROM dual
UNION
SELECT 1, 'Apr',20 FROM dual
UNION
SELECT 2, 'Jan',145 FROM dual
UNION
SELECT 2, 'Mar',50 FROM dual
UNION
SELECT 3, 'May',100 FROM dual
UNION
SELECT 4, 'Feb',250 FROM dual
)     
SELECT id_, mon, value_ 
FROM (
     SELECT id_, mon, value_ FROM t
     UNION 
     SELECT id_, mon ||'-Reversal', value_ * -1 FROM T WHERE MON = 'Feb'
)
ORDER BY id_;
于 2013-10-04T09:59:16.437 回答