我有一个名为user_var的下表
User_ID VAR_ID VALUE START_DATE END_DATE
1 25 2.0 01-JAN-2009 31-DEC-2011
1 56 4.56 01-JAN-2009 31-DEC-2011
1 89 7.8 01-JAN-2009 31-DEC-2011
2 25 5.64 01-OCT-2009 30-SEPT-2012
2 56 4.86 01-OCT-2009 30-SEPT-2012
2 89 9.87 01-OCT-2009 30-SEPT-2012
1 25 6.33 01-JUL-2009 30-JUN-2012
1 56 4.78 01-JUL-2009 30-JUN-2012
1 89 1.2 01-JUL-2009 30-JUN-2012
2 25 7.21 01-JAN-2009 31-DEC-2011
2 56 2.33 01-JAN-2009 31-DEC-2011
2 89 1.65 01-JAN-2009 31-DEC-2011
1 25 7.89 01-APR-2009 31-MAR-2012
1 56 0.00 01-APR-2009 31-MAR-2012
1 89 1.78 01-APR-2009 31-MAR-2012
2 25 7.6 01-JUL-2009 30-JUN-2012
2 56 7.15 01-JUL-2009 30-JUN-2012
2 89 8.54 01-JUL-2009 30-JUN-2012
我想在时间间隔内基于VAR_ID透视表 假设VAR_ID 25代表Credit VAR_ID 56代表借记卡 和VAR_ID 89代表余额
输出应该是
USER_ID CREDIT DEBIT BALANCE START_DATE END_DATE
1 2.0 4.56 7.8 01-JAN-2009 31-DEC-2011
2 5.64 4.86 9.87 01-OCT-2009 30-SEPT-2012
1 6.33 4.78 1.2 01-JUL-2009 30-JUN-2012
2 7.21 2.33 1.65 01-JAN-2009 31-DEC-2011
1 7.89 0.00 1.78 01-APR-2009 31-MAR-2012
2 7.6 7.15 8.54 01-JUL-2009 30-JUN-2012
答案 0 :(得分:1)
条件聚合
SELECT
u.user_id
,SUM(CASE WHEN var_id = 25 THEN u.Value END) AS Credit
,SUM(CASE WHEN var_id = 56 THEN u.Value END) AS Debit
,SUM(CASE WHEN var_id = 89 THEN u.Value END) AS Balance
,Start_Date
,End_Date
FROM
user_var u
GROUP BY
u.user_id
,start_date
,end_date