Keep zero values with GROUP BY and SUM in mysql

旧街凉风 提交于 2021-01-29 05:23:04

问题


I have two tables career_types and bookings

career_types

id | name
1 | foo
2 | bar
3 | baz

bookings

id | career_type_id | details
1 | 1 | foo
2 | 1 | bar
3 | 2 | baz

My bookings table has a lot of entries for all career types except career_types.id of 3.

I want a query that will list all my career_types.name's and how many each booking has, and in the case of career_types.id = 1 where there are no bookings for it. I want to return 0.

So far I've been trying variations of

SELECT career_types.name, sum(bookings.id)
FROM career_types
LEFT JOIN bookings ON (career_types.id = bookings.career_type_id)
GROUP BY career_types.id

And the result I'm looking for is

career_types.name | sum
foo | 2
bar | 1
baz | 0

But at the moment I'm not able to get any output for baz.


回答1:


Aggregate functions only include non-null values in their calculations. In the case of SUM, and most aggregate functions, the result is null if no non-null values are encountered. If zero is needed, rather than null, this can be accounted for simply with: IFNULL(SUM(x), 0)



来源:https://stackoverflow.com/questions/52174105/keep-zero-values-with-group-by-and-sum-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!