【发布时间】:2011-12-05 13:51:53
【问题描述】:
对于 Postgresql 8.x,我有一个包含 (id, user_id, question_id, choice) 的 answers 表,其中 choice 是一个字符串值。我需要一个查询,它将为所有唯一的choice 值返回一组记录(返回所有列)。我正在寻找的是每个独特选择的单一代表性记录。我还希望有一个聚合的votes 列,它是与每条记录附带的每个唯一选择匹配的记录数的count()。我想强制 choice 小写以便进行比较 (HeLLo 和 Hello 应该被视为相等)。我不能GROUP BY lower(choice) 因为我想要结果集中的所有列。按所有列分组会导致返回所有记录,包括所有重复项。
1。离我最近的
select lower(choice), count(choice) as votes from answers where question_id = 21 group by lower(choice) order by votes desc;
问题在于它不会返回所有列。
lower | votes
-----------------------------------------------+-------
dancing in the moonlight | 8
pumped up kicks | 7
party rock anthem | 6
sexy and i know it | 5
moves like jagger | 4
2。尝试所有列
select *, count(choice) as votes from answers where question_id = 21 group by lower(choice) order by votes desc;
因为我没有在GROUP BY 中指定SELECT 中的每一列,所以这会引发一个错误,告诉我这样做。
3。指定GROUP BY 中的所有列
select *, count(choice) as votes from answers where question_id = 21 group by lower(choice), id, user_id, question_id, choice order by votes desc;
这只是将所有记录的votes 列转储为1 的表。
如何从 1. 中获取 vote 计数和唯一代表记录,但返回表中的 所有 列?
【问题讨论】:
标签: postgresql