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.
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)
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
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)
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
精彩评论