日期:2014-05-17 浏览次数:20541 次
IF OBJECT_ID('T') IS NOT NULL DROP TABLE T
GO
CREATE TABLE T
(
ID INT IDENTITY(1,1) PRIMARY KEY,
NUM NVARCHAR(50),
MName nvarchar(50),
MNum int ,
MScore decimal(18,1)
)
go
INSERT INTO T
SELECT '20120508','煤炭1',8,2 UNION ALL
SELECT '20120508','煤炭1',8,4.5 UNION ALL
SELECT '20120508','煤炭1',8,5.6 UNION ALL
SELECT '20120508','煤炭1',8,6.2 UNION ALL
SELECT '20120508','煤炭1',8,6.3 UNION ALL
SELECT '20120508','煤炭1',8,8.2 UNION ALL
SELECT '20120508','煤炭1',8,9.5 UNION ALL
SELECT '20120508','煤炭1',8,10 UNION ALL
SELECT '20120509','煤炭6',8,9.2 UNION ALL
SELECT '20120509','煤炭6',8,10 UNION ALL
SELECT '20120510','煤炭7',8,9 UNION ALL
SELECT '20120510','煤炭7',8,9.8 UNION ALL
SELECT '20120511','煤炭8',8,9.2 UNION ALL
SELECT '20120511','煤炭8',8,9.9
GO
--第一种,
SELECT * FROM(
SELECT RIndex=ROW_NUMBER() OVER(PARTITION BY NUM ORDER BY ID desc),* FROM T
) TBL WHERE RIndex=1
GO
--第二种
;WITH CTE AS
(
SELECT MAXID=MAX(ID) FROM T B GROUP BY NUM
)
SELECT * FROM T WHERE EXISTS
(SELECT * FROM CTE B WHERE T.ID=B.MAXID)
GO
--第三种
SELECT * FROM T WHERE EXISTS
(SELECT MAXID FROM (SELECT MAXID=MAX(ID) FROM T GROUP BY NUM) B WHERE T.ID=B.MAXID)