4

I have a table numberoffirms like this:

--------------------------------------------
| id | region | month | year |    value    |
--------------------------------------------
|   1|       1|      1|     1|      1024001|
|   2|       1|      7|    25|        33542|
|   3|       1|      3|    26|     10000000|
|   4|       1|      5|    26|         1995|
|   5|       2|      4|    16|       123456|

My problem is that I need to get the highest value per region based on highest month and year. For example, from the table above, i should get the value 1995 because in region 1, the max year is 26 and in that year, the max month is 5.

Now when i run this SQL query which i made, it does not get the right value.

SELECT region, MAX(month) month, year, value FROM `numberoffirms` WHERE year IN (SELECT MAX(year) year FROM `numberoffirms` GROUP BY region) GROUP BY region

The value it gets is this

| region | month | year |   value  |
------------------------------------
|       1|      5|    26| 10000000 |

which is clearly wrong since the value i should get is 1995, though it got the region, month, and year correct.

What am i doing wrong with my SQL query code here?

2 Answers 2

1

You can simply use order by and limit 1 in a sub query:

Select * from numberoffirms t1 where id=
  (SELECT id FROM numberoffirms t2 
  where t1.region=t2.region
  order by year desc,month desc,value desc
  limit 1);

I created your table and values in my PC and tested the query and it works correctly.

Sign up to request clarification or add additional context in comments.

Comments

0

In MySql it is a little bit complicated:

select n2.* from numberoffirms n2
join(
      select n1.region, n1.year, max(n1.month) as month numberoffirms n1
      join (select region, max(year) as year from numberoffirms group by region) s1
         on n1.region = s1.region and n1.year = s1.year
      group by n1.region, n1.year) s2 
  on n2.region = s2.region and n2.year = s2.year and n2.month = s2.month

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.