我创建了此查询来选择前 14 个月的日期和金额,在这种情况下,如果该月没有记录,则该月份会丢失。如果该特定月份是,请建议我添加零和月份的解决方案失踪了。
SELECT dtSubscriptionRenewalDate,
DATE_FORMAT(dtSubscriptionRenewalDate, "%b %Y") AS month,
SUM(intPaymentAmount) as total
FROM `tbl_pi_payment`
WHERE strCurrencyCode = 'USD'
and dtSubscriptionRenewalDate <= NOW()
and dtSubscriptionRenewalDate >= Date_add(Now(),interval - 14 month)
group by month
ORDER BY `tbl_pi_payment`.`dtSubscriptionRenewalDate` ASC;
从结果中可以看到,NOv 2018 缺失了。
最佳答案
使用可能月份的选择/联合创建一个临时表,然后从中左连接您的表,仅选择给定月份的记录。为了方便起见,从几个月前计算日期范围(但您可以在连接中使用更复杂的表达式来表示开始日期和结束日期)。
select
min(dtSubscriptionRenewalDate) as min_renewal_date,
date_format(date_sub(now(), interval months_ago month), "%b %Y") as month,
coalesce(sum(intPaymentAmount),0) as total
from (
select
months_ago,
date(date_format(date_sub(now(), interval months_ago month), "%Y-%m-01")) start_date,
date(date_format(date_sub(now(), interval months_ago-1 month), "%Y-%m-01")) end_date
from (select 0 months_ago union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 10 union select 11 union select 12 union select 13 union select 14 order by months_ago) months_ago
) date_range
left join tbl_pi_payment on
dtSubscriptionRenewalDate >= start_date and
dtSubscriptionRenewalDate < end_date and
dtSubscriptionRenewalDate <= now() and
strCurrencyCode = 'USD'
group by months_ago desc;
这将报告 NULL 作为没有记录的月份的续订日期,以及有记录的月份的最小续订日期。不确定你到底想要什么。
关于mysql - SQL 查询选择前 14 个月,如果缺少任何月份,则添加金额 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59208142/