mysql - 在特定时间段内按 sql 分组显示零

标签 mysql sql

我正在尝试运行以下查询以获取特定时期内每种工作类型的销售额。但是,对于没有执行特定工作类型的工作的某些月份,销售额中不会显示 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/

相关文章:

MySQL 锁定与 SQLite 锁定

php - 未定义索引 : submission with html5

php - PDO 语句 (MySQL) : inserting value 0 into a bit(1) field results in 1 written in table

sql - 有没有办法将表名指定为字符串?

c# - 在 ASP.Net 应用程序中安全地存储(加密)数据

mysql - sql查询去掉min和max

php - 以原子方式调用 Web 服务?

sql - 聚合返回 * 作为数组

sql - 如果列中有日期和时间,如何检查当前日期?

mysql - 如何对多个列进行排名?