SQL:选择与其父查询相反的子查询,其中包括条件

时间:2014-10-15 14:02:48

标签: mysql sql

invoice_payments

invoice_id amount type
         1  10.00 Cash
         1   5.00 Cash
         1   5.00 Cash
         2  70.00 Store
         2  30.00 Cash

我希望获得总金额为现金和总金额为type = store

的行

我正在使用此查询:

SELECT invoice_id, SUM( amount ) AS total_paid, (
SELECT SUM( amount )  FROM invoice_payments WHERE TYPE =  'store' ) AS total_store
FROM invoice_payments  where type!='Store'
GROUP BY invoice_id

结果:

invoice_id total_paid total_store
         1      20.00       70.00
         2     100.00       70.00

期望的结果:

invoice_id total_paid total_store
         1      20.00       0.00
         2     100.00       70.00

正如您所看到的,total_store字段不是正确的值。请提出最佳解决方案。

我真的很感激任何回复。

由于

3 个答案:

答案 0 :(得分:2)

invoice_id p中选择amount,(选择总和(payments),其中p.invoice_id = a.invoice_id)'total_paid',(选择总和(amount))来自payments c其中c.invoice_id = a.invoice_id和type ='store')'total_store'来自payments一个群组invoice_id

答案 1 :(得分:1)

最好在这里使用case语句而不是子查询:

SELECT
    invoice_id,
    Sum(amount) as total_paid,      
    Sum(CASE WHEN type='store' THEN amount ELSE 0 END) as Store_Total        
FROM
    invoice_payments
GROUP BY invoice_id

答案 2 :(得分:0)

SELECT x.invoice_id
     , SUM(x.amount) total_paid
     , SUM(CASE WHEN x.type = 'store' THEN x.amount ELSE 0 END) total_store 
  FROM invoice_payments x 
 GROUP 
    BY x.invoice_id;