--建立測試環境 Create Table TEST (ID Int, 月份 Varchar(10), 年份 Int) Insert TEST Select 1, '12', 2005 Union All Select 2, '01', 2006 Union All Select 3, '02', 2006 Union All Select 4, '03', 2006 Union All Select 5, '04', 2006 Union All Select 6, '06', 2006 GO --測試 Select TOP 1 * From TEST A Where (Select Count(*) From TEST Where 月份<=A.月份 And 年份=A.年份)=月份 Order By 年份 Desc,月份 Desc GO --刪除測試環境 Drop Table TEST --結果 /* ID 月份 年份 5 04 2006 */
Create Table TEST
(ID Int,
月份 Varchar(10),
年份 Int)
Insert TEST Select 1, '12', 2005
Union All Select 2, '01', 2006
Union All Select 3, '02', 2006
Union All Select 4, '03', 2006
Union All Select 5, '04', 2006
Union All Select 6, '06', 2006
GO
--測試
Select TOP 1 * From TEST A Where (Select Count(*) From TEST Where 月份<=A.月份 And 年份=A.年份)=月份 Order By 年份 Desc,月份 Desc
GO
--刪除測試環境
Drop Table TEST
--結果
/*
ID 月份 年份
5 04 2006
*/