我正在尝试创建包含按年份区分的计算属性的查询。从 2007 年开始至今年。我的 sql 的简化示例:
SELECT users.id as id
users.name as name
SUM(CASE WHEN posts.approved = 1) AND posts.created_at BETWEEN '2007-01-01 00:00:00 +0100' AND '2007-12-31 23:59:59 +0100' THEN posts.ratings ELSE 0 END) as approved_rating_2007
SUM(CASE WHEN posts.approved = 0) AND posts.created_at BETWEEN '2007-01-01 00:00:00 +0100' AND '2007-12-31 23:59:59 +0100' THEN posts.ratings ELSE 0 END) as rejected_rating_2007
SUM(CASE WHEN posts.approved = 1) AND posts.created_at BETWEEN '2008-01-01 00:00:00 +0100' AND '2008-12-31 23:59:59 +0100' THEN posts.ratings ELSE 0 END) as approved_rating_2008
SUM(CASE WHEN posts.approved = 0) AND posts.created_at BETWEEN '2008-01-01 00:00:00 +0100' AND '2008-12-31 23:59:59 +0100' THEN posts.ratings ELSE 0 END) as rejected_rating_2008
etc...
FROM users
LEFT OUTER JOIN posts ON posts.user_id = users.id
有没有办法在某种循环中编写它,该循环总是包含从 2007 年到 current_year 的记录?