我有一张包含以下字段和数据的表格。
RefNo Year Month Code
1 2010 7 A
2 2009 10 B
3 2010 8 A
4 2010 5 B
从这里我可以找出特定代码的最大值(年,月)。 结果必须是
3 2010 8 A
1 2010 7 B
请帮我解决这个问题。
答案 0 :(得分:2)
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
编辑现在,对于在MySQL中工作的版本......
SELECT
*
FROM
myTable
WHERE
Year * 12 + Month = (SELECT MAX(Year * 12 + Month) FROM myTable AS lookup WHERE Code = myTable.Code)
编辑访问SQL后,可以确认这更快......
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)
答案 1 :(得分:1)
这对你有用吗?我们的想法是将Year和Month组合成SQL可以获取MAX的内容,然后将表连接到自身的这个修改版本。
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
这个想法在这里有更详细的解释:http://www.techonthenet.com/sql/max.php
答案 2 :(得分:0)
假设您的表名是“table1”,那么
select * from
(select * from table1 where Year in (select max(Year) from table1)) abc
where Month not in (select min(Month) from abc)
答案 3 :(得分:0)
我有解决方案:
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