0

我有一个包含以下字段和数据的表。

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

请帮我解决这个问题。

4

4 回答 4

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)
于 2011-06-20T16:36:34.007 回答
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

于 2011-06-20T16:22:23.767 回答
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) 
于 2011-06-20T16:19:37.400 回答
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
于 2011-06-22T09:19:15.777 回答