我正在尝试创建包含以年为单位的计算属性的查询。从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的记录?
答案 0 :(得分:4)
SELECT u.id,
u.name,
year(p.created_at) as create_year
SUM(CASE WHEN p.approved = 1 then p.ratings else 0 end) as approved_rating,
SUM(CASE WHEN p.approved = 0 then p.ratings else 0 end) as rejected_rating
FROM users u
LEFT OUTER JOIN posts p ON p.user_id = u.id
group by u.id, u.name, create_year