RDBMS - SQL Max基于另一列的唯一性的列的值

时间:2011-01-03 20:51:45

标签: sql rdbms

这是一个非常难以回答的问题。所以这里。以下sql:

select * from Survey_Answers 
where QuestionID='50a350a5-9f53-4f1a-83b8-485de45ac9a9'  
order by MaxRating

生成以下内容:

QuestionID                             Answer     Value MaxRating MinRating
--------------------------------------------------------------------------
50a350a5-9f53-4f1a-83b8-485de45ac9a9   anywhere       0     1         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   anyplace       0     2         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   test           9     2         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   love           10    3         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   no one         10    4         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   feel this way  0     5         0

(6 row(s) affected)

在MaxRating列中有两个“2”。我想要这两列的最大值。因此,例如,如果有三个1,两个2和五个4,我希望“值”列的最大值基于不同的最大列。

我希望这是有道理的,所以结果应该是:

而不是上述结果
QuestionID                             Answer     Value MaxRating MinRating
--------------------------------------------------------------------------
50a350a5-9f53-4f1a-83b8-485de45ac9a9   anywhere       0     1         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   test           9     2         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   love           10    3         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   no one         10    4         0
50a350a5-9f53-4f1a-83b8-485de45ac9a9   feel this way  0     5         0

9是基于具有“2”

数据的Maxrating列的“Value”列的最大值

这很难解释,所以我希望有人理解这一点。任何帮助都很高兴。任何重新措辞的帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:2)

这样的事情:

select *
from Survey_Answers sa1
where sa1.QuestionID = '50a350a5-9f53-4f1a-83b8-485de45ac9a9'  
and sa1.value = (select max(value) 
                 from Survey_Answers sa2
                where sa2.questionid = sa1.QuestionID
                  and sa2.maxrating = sa1.maxrating)
order by MaxRating