如何在单个查询中使用IF()语句获取单独的字段数据

时间:2014-02-05 10:54:12

标签: mysql sql

我试图在单个查询中单独获得未支付和部分金额

select 
    if(i.status = 'unpaid', sum(i.total_amount), '') unpaid, 
    if(i.status = 'partial', sum(i.paid_amount), '') partial 
from {CI}invoices i 
where 
    i.customer_id = ? and 
    date(i.invoice_date) < '2014-01-01' and 
    i.status not like 'paid%'

但是我变得空白我认为这是因为我在if语句中使用了'',我也试过了

if(i.status = 'unpaid', sum(i.total_amount) as unpaid, sum(i.paid_amount) as paid)  

这是错误的,因为我无法在as条件下使用IF()。任何人都可以帮我解决这个问题或建议任何其他方式??

3 个答案:

答案 0 :(得分:1)

尝试以下方法:

SELECT
    SUM( IF(i.status = 'unpaid', i.total_amount, 0) ) unpaid, 
    SUM( IF(i.status = 'partial', i.paid_amount, 0) ) partial 
FROM {CI}invoices i 
WHERE
    i.customer_id = ? AND
    date(i.invoice_date) < '2014-01-01' AND
    i.status IN ('unpaid', 'partial')

答案 1 :(得分:0)

放手一搏:

select 
    sum(case when i.status = 'unpaid' then i.total_amount else 0 end) as unpaid, 
    sum(case when i.status = 'partial' then i.paid_amount else 0 end) as partial 
from {CI}invoices i 
where 
    i.customer_id = ? and 
    date(i.invoice_date) < '2014-01-01' and 
    i.status not like 'paid%'

答案 2 :(得分:0)

您必须将表连接到自身才能在同一行中获得付款和取消付款:

SELECT 
    sum(iu.total_amount) unpaid, 
    sum(ip.paid_amount) partial 
FROM {CI}invoices iu
   CROSS JOIN {CI}invoices ip
where 
    ip.customer_id = ? AND iu.customer_id = ? AND
    date(ip.invoice_date) < '2014-01-01' AND date(iu.invoice_date) < '2014-01-01' AND
    iu.status = 'unpaid' AND ip.status = 'partial'