find maximum of set of columns for multiple rows in mysql query

馋奶兔 提交于 2020-01-03 05:56:29

问题


I have a table with the following fields and data.

RefNo Year Month Code
1     2010  7     A
2     2009  10    B
3     2010  8     A
4     2010  5     B

From this i've to find out the maximum(year, month) for a particular code. The result must be

3   2010  8 A
1   2010  7 B

Please help me solve this.


回答1:


SELECT
  *
FROM
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Year DESC, Month DESC) AS row_number,
    *
  FROM
    myTable
)
  AS orderedTable
WHERE
  row_number = 1


EDIT And now for a version that WORKS in MySQL...

SELECT
  *
FROM
  myTable
WHERE
  Year * 12 + Month = (SELECT MAX(Year * 12 + Month) FROM myTable AS lookup WHERE Code = myTable.Code)

EDIT After access to SQL, can confirm this is faster...

WHERE
    Year  = (SELECT MAX(Year)  FROM myTable AS lookup WHERE Code = myTable.Code)
AND Month = (SELECT MAX(Month) FROM myTable AS lookup WHERE Code = myTable.Code AND Year = myTable.Year)



回答2:


Does this work for you? The idea is to combine Year and Month into something that SQL can take the MAX of, then join the table to this modified version of itself.

SELECT OriginalTable.RefNo, OriginalTable.Year, OriginalTable.Month, OriginalTable.Code
FROM table OriginalTable,
     (SELECT Code, MAX(Year*100 + Month) AS CombinedDate
      FROM table
      GROUP BY Code) AS MaximumResults
WHERE OriginalTable.Code = MaximumResults.Code
AND OriginalTable.Year = MaximumResults.CombinedDate / 100
AND OriginalTable.Month = MaximumResults.CombinedDate % 100

The idea is explained more thoroughly here: http://www.techonthenet.com/sql/max.php




回答3:


Say your table name is "table1" then

select * from
(select * from table1 where Year in (select max(Year) from table1)) abc
where Month not in (select min(Month) from abc) 



回答4:


I've got the solution:

Select Month(B.NewDate) Mon, Year(B.NewDate) Year, Code, PK
from T1 A ,
(Select Max(Str_To_Date(Concat('01',',',Month,',',Year), '%d,%m,%Y')) as NewDate, Code C
from T1 group by Code) B
Where PK = (Select PK from T1
                where Year = Year(B.NewDate) and Month = Month(B.NewDate)  and Code = A.Code)
and A.Code = C
group by Code


来源:https://stackoverflow.com/questions/6414147/find-maximum-of-set-of-columns-for-multiple-rows-in-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!