【问题标题】:Mysql Fetch Records Based on Multiple CasesMysql基于多种情况获取记录
【发布时间】:2016-10-01 12:06:18
【问题描述】:

我确实有 Mercer_credit_history 表,我在其中存储商家信用、借记和交易类型。

我想根据交易类型对 CREDIT 或 DEBIT 求和。

记录

我试过这个:

选择 SUM(ABS(debit)) 作为 dealer_credit FROM Mercer_credits_history WHERE transaction_type='premium_debit'和merchant_id='x'

联合

SELECT SUM(ABS(credit)) as dealer_margin_earned FROM Mercer_credits_history WHERE transaction_type='margin_credit'和merchant_id='x'

并得到输出

如果我能有更好的查询以及单独的键值对中的值,我将不胜感激

【问题讨论】:

    标签: mysql database


    【解决方案1】:
    SELECT 
        SUM(CASE(WHEN transaction_type='premium_debit') THEN debit ELSE 0)) as dealer_credit, 
        SUM(CASE(WHEN transaction_type='margin_credit') THEN credit ELSE 0)) as dealer_margin_earned 
        FROM merchant_credits_history 
        WHERE merchant_id='x';
    

    因此,您会为每个商家 ID 获得一对贷记、借记值。

    【讨论】:

      【解决方案2】:
      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')
      

      【讨论】:

        【解决方案3】:

        试试这个:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-05-23
          • 1970-01-01
          • 1970-01-01
          • 2016-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多