PostgreSQL 数据分析/聚合
我在 PostgreSQL 中有一个表,其结构如下: 数据:
Question | Answer | Responses
---------------------------------------
Burger BigMac 8
Burger Whopper 19
Burger Cheeseburger 4
Drink Coke 22
Drink Water 1
Drink Juice 7
Side Salad 8
Side Fries 19
如何运行一个查询,返回每个“问题”的“答案”和最高“响应”? 对于上述数据,我希望看到类似的内容:
Question | Answer | Responses
---------------------------------------
Burger Whopper 19
Drink Coke 22
Side Fries 19
对于每个“问题”获得最高的“响应”我没有任何问题,但提取相关的“答案”被证明是一个问题。 用于获取 Question & 的 SQL 最高的回应是:
SELECT Question, MAX(Responses) FROM mytable GROUP BY Question;
任何人都可以阐明我的等式的最后部分 - 显示相关答案吗?
我已经尝试过这个:
SELECT Question, Answer, MAX(Responses) FROM mytable GROUP BY Question;
但是 Postgres 抱怨 Answer 没有在聚合或 GROUP BY 语句中使用。 我是否只需要事先确定所有问题,然后对每个问题进行 SQL 查询即可找到回答最多的答案? 我不想走这条混乱的路,但我想这是一个选择。
谢谢!
I have a table in PostgreSQL with the following structure & data:
Question | Answer | Responses
---------------------------------------
Burger BigMac 8
Burger Whopper 19
Burger Cheeseburger 4
Drink Coke 22
Drink Water 1
Drink Juice 7
Side Salad 8
Side Fries 19
How can I run a query that returns the 'Answer' with the higest 'Responses' for each 'Question'? For the above data I'd want to see something like:
Question | Answer | Responses
---------------------------------------
Burger Whopper 19
Drink Coke 22
Side Fries 19
I don't have any problems getting the higest 'Response' foreach 'Question', but also pulling out the relevant 'Answer' is proving to be a problem. The SQL that works to get the Question & highest response is:
SELECT Question, MAX(Responses) FROM mytable GROUP BY Question;
Can anybody shed any light on the last part of my equation - showing the relevant Answer?
I have tried this:
SELECT Question, Answer, MAX(Responses) FROM mytable GROUP BY Question;
however Postgres complains that Answer isn't being used in an aggregate or GROUP BY statement. Do I just need to determine all my questions beforehand, then do a SQL query for each question to find the answer with the most responses? I'd rather not go down this messy path, but it's an option I guess.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种标准方法是使用窗口函数。 不幸的是,这需要 8.4,但如果你可以尝试一下,类似这样的东西应该可以工作:
One standard way to do this is using window functions. Unfortunately this requires 8.4, but if you can try that, something like this should work:
注意:最初的问题不够具体,因为可能有多个答案,且具有最大响应数(每个问题)。
Note: the original question is under-specificied as there can be more then one answer with the max number of responses (per question).