如何在sql表中合并(获得总和)一些重复数据?

时间:2015-11-09 09:57:16

标签: sql database oracle

在完成一些查询之后,我在oracle SQL开发人员身上获得了以下结果。 figure 1

但我需要这样:

[figure 2]

我想将它与每个User_ID的Cash_IN和Cash_out中的总和合并。

这是我用来获得上层(第一个数字)结果的SQL查询:

SELECT User_ID, Cash_In, Cash_out 
FROM (SELECT wa.User_ID, count(tt.ID) Cash_In, 0 Cash_out 
      FROM mwt_wallet_transactions t, mwt_txn_types tt, mwt_user_wallet wa
       WHERE t.txn_code = tt.ID and
        t.a_number = wa.id and 
        tt.ID = '1'
        GROUP BY wa.User_ID)

UNION ALL

SELECT User_ID, Cash_In, Cash_out 
FROM (SELECT wa.User_ID, 0 Cash_In, count(tt.ID) Cash_out 
      FROM mwt_wallet_transactions t, mwt_txn_types tt, mwt_user_wallet wa
      WHERE t.txn_code = tt.ID and 
        t.a_number = wa.id and 
        tt.ID = '2'
      GROUP BY wa.User_ID)
ORDER BY User_ID;

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT User_ID, Cash_In, Cash_out 
FROM 
(SELECT wa.User_ID, count(case when tt.ID = '1' then 1 else null end) Cash_In,
        count(case when tt.ID = '2' then 1 else null end)  Cash_out 
FROM mwt_wallet_transactions t, mwt_txn_types tt, mwt_user_wallet wa
WHERE t.txn_code = tt.ID and
t.a_number = wa.id
GROUP BY wa.User_ID)
ORDER BY mobile_no;