Nasir Nasir - 6 months ago 8
MySQL Question

Case in where mysql not working

SELECT SUM(amount) as tdb
FROM (`v_ledger_details`)
WHERE `debit_credit` = 'DB'
AND `CASE` WHEN transaction_type_id IN(4,5)
THEN billDate < "2016-06-01"
ELSE postingDate < "2016-06-01"
END
AND accountId = '944'


what is worong with the above query. i need the case claues in where but that query give me error.

Answer

Don't use case in a where clause. Normally only use it in select clauses. And then don't backtick the case keyword

SELECT SUM(amount) as tdb 
FROM v_ledger_details
WHERE `debit_credit` = 'DB' 
AND accountId = '944'
AND 
(
    (transaction_type_id IN (4,5) and billDate < '2016-06-01') OR
    (transaction_type_id NOT IN (4,5) AND postingDate < '2016-06-01')
)
Comments