我有一个90%的查询,我正在查询一周中每一天的数据,这对于那里的数据工作正常但是我也喜欢那些不存在的数据(我希望查询在一周中不存在的日期中包含零。
SELECT EXTRACT(dow FROM start_at) AS number, COUNT(*) FROM "events" GROUP BY number
或用于铁路......
Event.select("EXTRACT(dow FROM start_at) AS number, COUNT(*)").group("number")
结果。
+----+--------+-------+
| id | number | count |
+----+--------+-------+
| | 0.0 | 16 | # day of the week Sunday
| | 1.0 | 20 |
| | 2.0 | 29 |
| | 3.0 | 19 |
| | 4.0 | 4 |
+----+--------+-------+
如何扩展此查询以映射一周中的所有日期,即使没有记录? (看起来像这样)。
+----+--------+-------+
| id | number | count |
+----+--------+-------+
| | 0.0 | 16 |
| | 1.0 | 20 |
| | 2.0 | 29 |
| | 3.0 | 19 |
| | 4.0 | 4 |
| | 5.0 | 0 | # i want these zeros too!
| | 6.0 | 0 |
+----+--------+-------+
答案 0 :(得分:0)
试试这个:
events = Event.select("EXTRACT(dow FROM start_at) AS number, COUNT(*)").group("number")
counts = events.each_with_object({}) do |event, counts|
counts[event.number.to_i] = event.count
end
weekdays = (0..6).map do |day|
{
number: day,
count: counts[day] || 0
}
end
即使计数为零,它也应该为您提供每天的哈希数组和当天的计数。我无法完全测试它,因为我没有你的数据库表,但希望它会指出你正确的方向。