我正在尝试运行以下查询以获取特定时期内每种工作类型的销售额。但是,对于没有执行特定工作类型的工作的某些月份,销售额中不会显示 0。
如何在这种情况下显示零。
这是sql查询-
select Year(postedOn), month(postedOn), jobType, sum(price)
from tbl_jobs
group by jobType, year(postedOn), month(postedOn)
order by jobType, year(postedOn), month(postedOn)
最佳答案
通常,这是您的通用日历或数字表用于使用一致的顺序集来锚定查询的地方:
SELECT job_summary.*
FROM Calendar
CROSS JOIN (
-- you may not have though about this part of the problem, though
-- what about years/months with missing job types?
SELECT distinct jobType FROM tbl_jobs
) AS job_types
LEFT JOIN (
select Year(postedOn) AS year,month(postedOn) as month,jobType ,sum(price)
from tbl_jobs
group by jobType, year(postedOn), month(postedOn)
) job_summary
ON job_summary.jobType = job_types.jobType
AND job_summary.year = Calendar.year
AND job_summary.month = Calendar.month
WHERE Calendar.day = 1 -- Assuming your calendar is every day
AND calendar.date BETWEEN some_range_goes_here -- you don't want all time, right?
order by job_types.jobType, Calendar.year, Calendar.month
关于mysql - 在特定时间段内按 sql 分组显示零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42592300/