基于多个案例的Mysql获取记录

时间:2016-10-01 12:06:19

标签: mysql database

我有merchant_credit_history表,我存储商家信用卡,借记卡和交易类型。

我希望根据交易类型对CREDIT或DEBIT进行汇总。

记录

enter image description here

我试过这个:

SELECT SUM(ABS(借记))为 dealer_credit 来自merchant_credits_history WHERE transaction_type ='premium_debit'和merchant_id ='x'

UNION

SELECT SUM(ABS(credit))为 dealer_margin_earned 来自merchant_credits_history WHERE transaction_type ='margin_credit'和merchant_id ='x'

并将其视为

enter image description here

如果我能有更好的查询以及单独的键值对中的值

,我将不胜感激

3 个答案:

答案 0 :(得分:0)

return

因此,您可以获得每个merchant_id的一对信用卡,借方值。

答案 1 :(得分:0)

SELECT SUM(Debit), SUM(CREDIT) FROM 
   (SELECT 
      CASE WHEN transaction_type='premium_debit' THEN debit ELSE 0 END as Debit, 
      CASE WHEN transaction_type='margin_credit' THEN credit ELSE 0 END as Credit
   FROM Customers WHERE merchant_id='x')

答案 2 :(得分:0)

试试这个:

SELECT SUM(ABS(credit)) as Credit, SUM(ABS(debit)) AS Debit, 
transaction_type FROM merchant_credits_history merchant_id='x'
GROUP BY (transaction_type);