我在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
我没有任何问题得到最高的'响应'foreach'问题',但也拉出相关的'答案'证明是一个问题。用于获取问题和解答的SQL最高的回应是:
SELECT Question, MAX(Responses) FROM mytable GROUP BY Question;
任何人都可以对我的等式的最后部分有所了解 - 显示相关的答案?
我试过这个:
SELECT Question, Answer, MAX(Responses) FROM mytable GROUP BY Question;
然而Postgres抱怨答案没有在聚合或GROUP BY语句中使用。我是否只需要事先确定我的所有问题,然后对每个问题进行SQL查询以找到答案最多的答案?我宁愿不走这条凌乱的道路,但我想这是一个选择。
谢谢!
答案 0 :(得分:4)
SELECT
DISTINCT ON (question)
question, answer, responses
FROM
mytable
ORDER BY
question, responses DESC;
答案 1 :(得分:2)
执行此操作的一种标准方法是使用窗口函数。不幸的是,这需要8.4,但是如果你可以尝试,那么这样的事情应该有效:
SELECT question, answer, responses
FROM (
SELECT question,answer,responses,row_number()
OVER (PARTITION BY question ORDER BY responses DESC)
FROM mytable
) AS t
WHERE row_number=1
答案 2 :(得分:0)
Select Answer
From mytable, (Select Question, max(Responses) as maxres
From mytable
Group by Questions) as Temp
Where mytable.Question = Temp.Question
and mytable.Responses = Temp.maxres
注意:原始问题没有特别说明,因为答案的最大数量(每个问题)可以有多个答案。