RDBMS - SQL Max Value of a column based on a different column uniqueness

This is a really tricky question. So here. Next sql:

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

Creates the following:

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)

There are two "2" in the MaxRating column. I would like to get the maximum value of these two columns. So, for example, if there were three 1s and two 2s and five 4s, I would like the maximum value of the "value" column to be based on separate maxrating columns.

Hope this makes sense, so instead the result should be:

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 is the maximum "Value" column based on the Maxrating column with data "2"

It is so difficult to explain, so I hope someone understands this. Any help is appreciated. Any help in re-wording would be great. Thank.

+3
source
1

- :

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
+2

Source: https://habr.com/ru/post/1783288/


All Articles