每个月的 GROUP BY 和 return 0 或 NULL 如果不存在月份 (MySQL)
GROUP BY for each Month and return 0 or NULL if not month exists (MySQL)
SELECT COALESCE(SUM(p.hours),0) as recap
FROM pointage p
WHERE YEAR(date_point) = '2020' AND p.user_id = 1
GROUP BY MONTH(date_point)
我想要每个月实现的总小时数,但实际上在 3 月,其他月份不存在,因为不存在我想要获得类似的结果(仅总和列,但仅作为示例)
Jan : NULL
Feb : 10
March : 42.75
APR : NULL
MAY : NULL
..
DEC : NULL
不仅如此
Feb : 10
March : 42.75
请问有解决办法吗?
如果您有 table 中所有月份的数据——但只是没有那个用户的数据——那么最简单(虽然不是最有效)的方法是条件聚合:
SELECT MONTH(date_point) as mon,
SUM(CASE WHEN p.user_id = 1 THEN p.hours END) as recap
FROM pointage p
WHERE YEAR(date_point) = 2020
GROUP BY MONTH(date_point) ;
否则,您需要一个月份列表,它可以通过多种方式生成——日历 table,递归 CTE,明确:
select m.mon, sum(p.hours)
from (select 'Jan' as mon, 1 as mm union all
select 'Feb' as mon, 2 as mm union all
. . .
) m left join
pointage p
on p.date_point >= '2020-01-01' and '2021-01-01' and
p.user_id = 1 and
month(p.date_point) = m.mm
group by m.mon
order by min(m.mm);
SELECT COALESCE(SUM(p.hours),0) as recap
FROM pointage p
WHERE YEAR(date_point) = '2020' AND p.user_id = 1
GROUP BY MONTH(date_point)
我想要每个月实现的总小时数,但实际上在 3 月,其他月份不存在,因为不存在我想要获得类似的结果(仅总和列,但仅作为示例)
Jan : NULL
Feb : 10
March : 42.75
APR : NULL
MAY : NULL
..
DEC : NULL
不仅如此
Feb : 10
March : 42.75
请问有解决办法吗?
如果您有 table 中所有月份的数据——但只是没有那个用户的数据——那么最简单(虽然不是最有效)的方法是条件聚合:
SELECT MONTH(date_point) as mon,
SUM(CASE WHEN p.user_id = 1 THEN p.hours END) as recap
FROM pointage p
WHERE YEAR(date_point) = 2020
GROUP BY MONTH(date_point) ;
否则,您需要一个月份列表,它可以通过多种方式生成——日历 table,递归 CTE,明确:
select m.mon, sum(p.hours)
from (select 'Jan' as mon, 1 as mm union all
select 'Feb' as mon, 2 as mm union all
. . .
) m left join
pointage p
on p.date_point >= '2020-01-01' and '2021-01-01' and
p.user_id = 1 and
month(p.date_point) = m.mm
group by m.mon
order by min(m.mm);