mysql - 如果特定月份没有记录,如何获得 0 条记录?
问题描述
我有查询,显示最近 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
谁能帮我解决这个问题?
解决方案
尝试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
推荐阅读
- c# - SOAP 服务器返回意外的操作
- webpack - Webpack4:如何处理子文件夹中的图像
- windows-services - 在 CI 服务器上运行时,testcafe E2E 测试在 Internet Explorer 11 上挂起(由 Windows 服务运行)
- python - 导出 svg 文件时,Plotly 无法访问 orca 服务器
- octobercms - 关系经理如何使用转发器字段?
- php - PHP在页面之间丢失会话
- c++ - 为什么 gcc 编译这个而 msvc 不编译
- c++ - 链表的通用函数 remove() 与成员函数 remove()
- java - 生成正则表达式以匹配字符串
- php - 用包含+符号的长字符串(超过1000个字符)在php中解码json字符串