按日期分组的循环变量 [英] Loop variable grouping by date
问题描述
我有一些体育比赛的结果,我想遍历这些结果并在表格中的日期下分组.例如;
I have some sporting results that i'd like to loop through and group under dates in a table. For example;
|Sat, 20|
|Game 1 Results|
|Game 2 Results|
|Sun, 21|
|Game 3 Results|
|Sat, 27|
|Game 4 Results|
我的控制器
@matches = Match.group([:matchId, 'DATE(matchDate)']).inject([]) do |results, matches|
team_names = Match.where(matchId: matches.matchId)
results << [matches.id, matches.matchDate, team_names.first.team.name, team_names.last.team.name, team_names.first.points, team_names.last.points]
end
目前我正在做一个基本的循环,正在显示.
At the moment i'm doing a basic loop, which is showing.
|Sat, 20|
|Game 1 Results|
|Sat, 20|
|Game 2 Results|
|Sun, 21|
|Game 3 Results|
|Sat, 27|
|Game 4 Results|
推荐答案
SQL GROUP BY
用于聚合值:您可以获得每个日期的匹配次数,或目标总和,等等上.(在此处阅读更多内容.)但如果您想要所有游戏的列表,请按组不太合适.
SQL GROUP BY
is for aggregating values: you can get the count of matches per date, or the sum of goals, and so on. (Read more here.) But if you want a list of all games in groups, it's not a good fit.
您看到两次相同的日期,因为您按日期和匹配 ID 分组.
You're seeing the same date twice because you're grouping by the date and the match ID.
如果你没有很多数据,你可以用 Ruby 代码来完成:
If you don't have a lot of data, you could do it all in Ruby code:
Match.all.group_by { |match| match.matchDate.to_date }
这为您提供了一个以日期为键、匹配列表为值的散列.
This gives you a hash with dates as keys and lists of matches as values.
此答案假定 matchDate
是时间,因为您在示例中使用了 DATE(matchDate)
.如果它已经是日期,则不需要上面的 .to_date
位.
This answer assumes that matchDate
is a time, because you used DATE(matchDate)
in your example. If it's already a date, you don't need the .to_date
bit above.
另请注意,SQL 中的DATE(a_time_column)
将提取数据库时区中的日期.Rails 通常将数据库配置为在内部使用 UTC 时区.因此,如果您确实使用这样的数据库查询,请注意这一点并确保您获得正确的日期.
Also note that DATE(a_time_column)
in SQL will extract the date in the database time zone. Rails often has the database configured to use the UTC time zone internally. So if you do go with a database query like that, be aware of this and make sure you get the right date.
这篇关于按日期分组的循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!