【问题标题】:Retrieving Representative Records for Unique Values of Single Column检索单列唯一值的代表记录
【发布时间】:2011-12-05 13:51:53
【问题描述】:

对于 Postgresql 8.x,我有一个包含 (id, user_id, question_id, choice)answers 表,其中 choice 是一个字符串值。我需要一个查询,它将为所有唯一的choice 值返回一组记录(返回所有列)。我正在寻找的是每个独特选择的单一代表性记录。我还希望有一个聚合的votes 列,它是与每条记录附带的每个唯一选择匹配的记录数的count()。我想强制 choice 小写以便进行比较 HeLLoHello 应该被视为相等)。我不能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


    【解决方案1】:

    将分组结果与主表连接起来,然后为每个(问题、答案)组合仅显示一行。

    类似这样:

    WITH top5 AS (
      select question_id, lower(choice) as choice, count(*) as votes 
      from answers 
      where question_id = 21 
      group by question_id , lower(choice) 
      order by count(*) desc
      limit 5
    )
    SELECT DISTINCT ON(question_id,choice) *
    FROM top5 
    JOIN answers USING(question_id,lower(choice))
    ORDER BY question_id, lower(choice), answers.id;
    

    【讨论】:

    • 感谢您的帮助和努力。请参阅我的答案以了解我最终在我的应用程序中使用的内容。
    【解决方案2】:

    这就是我最终得到的结果:

    SELECT answers.*, cc.votes as votes FROM answers join (
        select max(id) as id, count(id) as votes 
        from answers
        group by trim(lower(choice))
    ) cc 
    on answers.id = cc.id ORDER BY votes desc, lower(response) asc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 2016-05-19
      • 1970-01-01
      • 2011-12-03
      相关资源
      最近更新 更多