我希望在“月”列的值为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
请帮忙。
答案 0 :(得分: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
答案 1 :(得分: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_;