如何在mysql中检查两个条件

时间:2013-04-19 05:25:26

标签: mysql sql

select cust_code,occu_name
, SUM(CASE WHEN VoucherType = 'S' THEN Amount ELSE 0 END) AS salesSum
,SUM(CASE WHEN VoucherType = 'I' THEN Amount ELSE 0 END) AS interestSum
,SUM(CASE WHEN VoucherType = '' THEN Amount ELSE 0 END) AS interest_sum
,SUM(CASE WHEN VoucherType = 'P' THEN Amount ELSE 0 END) AS chequereturn_sum
,SUM(CASE WHEN VoucherType = 'R' THEN Amount ELSE 0 END) AS receipt_sum
,SUM(CASE WHEN VoucherType = 'R' THEN Amount ELSE 0 END) AS receipt_sum
,SUM(CASE WHEN VoucherType = 'N' THEN Amount ELSE 0 END) AS credit_sum
,SUM(CASE WHEN (DrCrType = 'DR' and VoucherDate <= '2012-04-01') THEN Amount ELSE (Amount*-1)) AS opening_sum
from bmwregistration, ledger_transactions
where bmwregistration.ledger_id = ledger_transactions.OccupierID and
  VoucherDate >= '2012-04-01' and
  VoucherDate <= '2013-02-01'
group by cust_code

如何检查求和函数SUM(CASE WHEN (DrCrType = 'DR' and VoucherDate <= '2012-04-01') THEN Amount ELSE (Amount*-1)) AS opening_sum

中的两个条件

3 个答案:

答案 0 :(得分:2)

你正在以正确的方式做到这一点。

See this Example

你刚才犯了一个小错误。您只需在这样的条件之后添加END

SUM(CASE WHEN DrCrType = 'DR' 
          and VoucherDate <= '2012-04-01' 
         THEN Amount 
         ELSE (Amount*-1) END) AS opening_sum
                          ^^^

所以你的整个查询应该是这样的:

select cust_code,occu_name
, SUM(CASE WHEN VoucherType = 'S' THEN Amount ELSE 0 END) AS salesSum
,SUM(CASE WHEN VoucherType = 'I' THEN Amount ELSE 0 END) AS interestSum
,SUM(CASE WHEN VoucherType = '' THEN Amount ELSE 0 END) AS interest_sum
,SUM(CASE WHEN VoucherType = 'P' THEN Amount ELSE 0 END) AS chequereturn_sum
,SUM(CASE WHEN VoucherType = 'R' THEN Amount ELSE 0 END) AS receipt_sum
,SUM(CASE WHEN VoucherType = 'R' THEN Amount ELSE 0 END) AS receipt_sum
,SUM(CASE WHEN VoucherType = 'N' THEN Amount ELSE 0 END) AS credit_sum
SUM(CASE WHEN DrCrType = 'DR' 
          and VoucherDate <= '2012-04-01' 
         THEN Amount 
         ELSE (Amount*-1) END) AS opening_sum
from bmwregistration, ledger_transactions
where bmwregistration.ledger_id = ledger_transactions.OccupierID and
  VoucherDate >= '2012-04-01' and
  VoucherDate <= '2013-02-01'
group by cust_code

答案 1 :(得分:1)

 WHEN PAT_DrCrType = 'DR' and VoucherDate <= '2012-04-01' THEN Amount ELSE (Amount-1)) AS opening_sum

答案 2 :(得分:1)

试试这种方式

SUM(CASE WHEN DrCrType = 'DR' AND VoucherDate <= '2012-04-01' THEN Amount ELSE (Amount-1) END)