Mysql Query使用if语句检索值

时间:2012-01-18 06:28:12

标签: mysql if-statement

select
      IFNULL(sum(invoice0_.INV_AMT),0)  as col_0_0_,IFNULL(sum(invoice1_.INV_AMT),0)  as col_0_0_
    from
        hrmanager.invoice invoice0_,
        hrmanager.invoice invoice1_
    where
         invoice0_.FROM_LEDGER=1
         **or** invoice1_.TO_LEDGER=1
        and (
            invoice0_.INV_DATE between '1900-12-20' and '2012-01-30'
        )
        and invoice0_.ACTIVE='Y'
        and invoice0_.COMP_ID=2
        and invoice1_.COMP_ID=2
        and invoice0_.INV_TYPE='CLIENT'
        and invoice1_.INV_TYPE='CLIENT';

这里我希望选择所有from_ledger = 1的总和,下一列应显示所有to_ledger = 1的总和,但这里给出和/或在条件中检索相同的数据,在Db这里从分类帐= 1然后结果是7000和toledger = 1然后它将为0,但上面的查询检索两列是相同的值,如0或7000

1 个答案:

答案 0 :(得分:0)

看起来你的查询有点混乱。您正在从同一个表中执行两次查询,但没有JOIN条件会导致笛卡尔结果。我认为你要找的是你的桌子“Invoice”里面有两列......“To_Ledger”和“From_Ledger”,“INV_AMT”以及其他一些标准字段...这应该让你更接近你的答案。

select
      sum( if( inv.From_Ledger = 1, inv.Inv_Amt, 0 )) as FromInvoiceAmounts,
      sum( if( inv.To_Ledger = 1, inv.Inv_Amt, 0 )) as ToInvoiceAmounts
   from
      hrmanager.invoice inv
   where
          1 in ( inv.From_Ledger, inv.To_Ledger )
      AND inv.inv_date between '1900-12-20' and '2012-01-30'
      and inv.Active = 'Y'
      and inv.Comp_ID = 2
      and inv.Inv_Type = 'CLIENT'