如果特定月份没有记录,如何获取0条记录?

时间:2018-11-26 12:11:52

标签: mysql mysqli

我有查询,显示最近12个月的记录,对我来说很好,但是我想显示该月也没有记录,如果特定月份没有记录,那么我想显示0条记录该月,我在这里添加了该查询

SELECT `amount`, CONVERT_TZ(created, "+00:00", "-05:00") as created, 
       MONTHNAME(CONVERT_TZ(created, "+00:00", "-05:00")) as month, 
       `sponsorion_fees`, `processor_fees`, `amount_after_fees`, 
       SUM(amount_after_fees) as total FROM `transaction` 
WHERE `record_owner_user_id` = '50' AND `is_one_time_purchase` = 'Y' 
       AND CONVERT_TZ(created,"+00:00","-05:00") <= "2018-11-26 07:08:24"
       and CONVERT_TZ(created,"+00:00","-05:00") >= 
       Date_add("2018-11-26 07:08:24",interval - 12 month)
GROUP BY `month` ORDER BY `id` ASC

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

尝试IFNULL

SELECT `amount`, CONVERT_TZ(created, "+00:00", "-05:00") as created,
                 MONTHNAME(CONVERT_TZ(created, "+00:00", "-05:00")) as month,
                 `sponsorion_fees`, `processor_fees`, `amount_after_fees`, 
                 SUM(IFNULL(amount_after_fees, 0)) as total FROM `transaction`
WHERE `record_owner_user_id` = '50' 
                     AND `is_one_time_purchase` = 'Y' 
                     AND CONVERT_TZ(created,"+00:00","-05:00") <= "2018-11-26 07:08:24" 
                     and CONVERT_TZ(created,"+00:00","-05:00") >= Date_add("2018-11-26 07:08:24",interval - 12 month)
GROUP BY `month` 
ORDER BY `id` ASC

也尝试COALESCE

SELECT `amount`, CONVERT_TZ(created, "+00:00", "-05:00") as created,
                     MONTHNAME(CONVERT_TZ(created, "+00:00", "-05:00")) as month,
                     `sponsorion_fees`, `processor_fees`, `amount_after_fees`, 
                     COALESCE(SUM(amount_after_fees),0) as total FROM `transaction`
    WHERE `record_owner_user_id` = '50' 
                         AND `is_one_time_purchase` = 'Y' 
                         AND CONVERT_TZ(created,"+00:00","-05:00") <= "2018-11-26 07:08:24" 
                         and CONVERT_TZ(created,"+00:00","-05:00") >= Date_add("2018-11-26 07:08:24",interval - 12 month)
    GROUP BY `month` 
    ORDER BY `id` ASC