Lowest ranked items out of those which have been ranked x times

时间:2018-03-25 20:16:36

标签: mysql sql apache-spark-sql

I have a sql dataset that look like this

Table df1:

+-----+------+---------+
| Key | Name | Ranking |
+-----+------+---------+
|   1 | A    |       2 |
|   2 | B    |       4 |
|   1 | A    |       3 |
+-----+------+---------+

I want to find the lowest ranked item which has been ranked atleast 5 times.

This is the code I have so far but it doesnt seem to work:

select 
     Key,
     Name,
     Ranking,
     sum(Ranking) 
from 
     table 
Group BY 
     key
Where 
     Count(Ranking)>5

2 个答案:

答案 0 :(得分:1)

What do you think about this:

SELECT
     id,
     Name,
     MIN(Ranking)   
FROM 
     table 
Group BY id 
HAVING SUM(Ranking) >= 5;

答案 1 :(得分:1)

[example]

SELECT
     key_,
     Name,
     MAX(Ranking),
     MIN(Ranking) 
FROM 
     df1 
GROUP BY key_ 
HAVING COUNT(Ranking) >= 5;

As you'll see in the example/demo, the first query on the table with no key having at least 5 rankings results in no rows. Then I've inserted 4 more records for key_=5 and then queried again, retrieving the result:

enter image description here

(included MAX() for the other Ranking in your example because you weren't using an ORDER BY so the result for Ranking in that case 'could' be random.)