如果特定月份不存在记录,我想获取数据

I want to get data if records are not present in specific month

我写了一个 sql 查询来获取特定月份发生的所有记录

select month(loggingdate),Count(id) from communicationlogs 
where clientid=20154 and month(loggingdate) in (1,2,3,4,5,6,7,8,9)
group by month(loggingdate)

7   65
8   5

这里的记录出现在第 7 个月和第 8 个月。我想为其他月份的数字获得 0 值,例如-

1   0
2   0
3   0
4   0
...

这是一个标准问题,日历 table 可以派上用场。顾名思义,日历 table 是一个仅存储一系列日期的 table。在您的特定情况下,我们只需要与 12 个月对应的数字。以日历 table 开始查询,然后作为子查询左连接到您的聚合查询。

注意下面COALESCE的用法。如果给定的月份在您的原始查询中没有出现,那么它的计数将在联接中显示为 NULL,在这种情况下,我们报告该月份为零。

WITH calendar_month AS (
    SELECT 1 AS month 
    UNION ALL
    SELECT month +1 
    FROM
    calendar_month
    WHERE month +1 <= 12
)

SELECT
    t1.month,
    COALESCE(t2.cnt, 0) AS cnt
FROM calendar_month t1
LEFT JOIN
(
    SELECT
        MONTH(loggingdate) as month,
        COUNT(id) AS cnt
        FROM communicationlogs 
        WHERE
            clientid = 20154 AND
            MONTH(loggingdate) IN (1,2,3,4,5,6,7,8,9)
        GROUP BY MONTH(loggingdate)
) t2
    ON t1.month = t2.month