SELECT
`ps_bonus_account`.`id_customer`,
SUM(IF(`status` = 1, `points`, - `points`) -
IF(
`status` = 1 AND `date_bonus_to` < NOW(),
GREATEST(0, `ps_bonus_account`.`points` - (
SELECT SUM(`points`)
FROM `ps_bonus_account` `used`
WHERE
`used`.`id_customer` = `ps_bonus_account`.`id_customer` AND `status` = 2 AND
`paid` = 1 AND `used`.`date_add` < `ps_bonus_account`.`date_bonus_to`
)),
0)) `balance`
FROM `ps_bonus_account`
WHERE
`id_customer` = 518 AND
`paid` = 1
GROUP BY `ps_bonus_account`.`id_customer`
;
SELECT VERSION();