同一查询中不同cols的多个和

时间:2016-06-03 12:34:28

标签: mysql join sum

如果内连接为真,是否可以对cols求和,如果另一个内连接为true,是否可以对另一个cols求和?即

SELECT t1.debit 
     , t2.credit  
     , t1.ID 
     , t2.ID 
  FROM
     ( SELECT SUM(booking_value) debit 
            , gl_acct.id_fin_gl_acct ID 
         FROM bookings 
         JOIN gl_acct 
           ON (CONCAT('1',gl_acct.id_fin_gl_acct) = bookings.id_debit_account)
     ) t1 
  JOIN 
     ( SELECT SUM(booking_value) credit 
            , gl_acct.id_fin_gl_acct ID 
         FROM bookings 
         JOIN gl_acct 
           ON (CONCAT('1',gl_acct.id_fin_gl_acct)=bookings.id_credit_account)
     ) t2
    ON (t1.ID = t2.ID)
 GROUP  
    BY t1.ID

请解释你的答案。

1 个答案:

答案 0 :(得分:1)

条件聚合的一个例子。

 SELECT t.id_account
      , SUM(IF(t.cr_or_db='cr',t.tot_booking_value,0)) AS `tot_credit` 
      , SUM(IF(t.cr_or_db='db',t.tot_booking_value,0)) AS `tot_debit`
   FROM ( 
          SELECT 'cr'                  AS `cr_or_db`
               , c.id_credit_account   AS `id_account`
               , SUM(c.booking_value)  AS `tot_booking_value`
            FROM bookings c
           GROUP BY c.id_credit_account
           UNION ALL
          SELECT 'db'                  AS `cr_or_db`
               , d.id_debit_account    AS `id_account`
               , SUM(d.booking_value)  AS `tot_booking_value`
            FROM bookings d
           GROUP BY d.id_debit_account
        ) t
  GROUP 
     BY t.id_account 

内联视图t为每个id_credit_account获取总余额,并为每个id_debit_account获取总借记。

原始查询将这两个id_列连接到同一个帐户表,因此我们假设这些都是该另一个表的外键,这意味着它们是相同的数据类型...

只有在我们需要包含gl_acct表的某些原因时才需要加入操作。假设id_fin_gl_acct中的gl_acct是UNIQUE ...我们可以在GROUP BY子句之前添加连接操作。

    ...   
        ) t

   JOIN gl_acct g
     ON CONCAT('1',g.id_fin_gl_acct) = t.id_account 

  GROUP 
     BY t.id_account