I have this table (simplified version):
id | state | place | temp |
---|---|---|---|
1 | AA | PLC1 | 10 |
2 | AA | PLC2 | 20 |
3 | AA | PLC3 | 25 |
4 | EE | PLC4 | 11 |
5 | EE | PLC5 | 15 |
6 | EE | PLC6 | 19 |
. | .. | …. | .. |
How to find top 2 hottest places (based on temp column) from X states ?
The states will be provided during query time, i.e there may be 2 or 5 states which is not known in advance.
4
Answers
The following query shall give you the desired result
Here is the SQLFIDDLE using your sample data.
The query :
Returns correct output as :
The query can be also written using
ROW_NUMBER
withPARTITION BY
clause as in this demo :You can use
ROW_NUMBER
withpartition by
clause:If you have Mysql 8, check out ranking functions. For example you can use dense_rank() to also account for ties.
fiddle
You can do it using
rank()
ordense_rank
, this will return more than 2 top places if there are places with the same temp,If this what you want then try this :
Demo here