使用ROW_NUMBER你可以嘗試
DECLARE @Table TABLE(
Flag VARChAR(1),
Zone VARCHAR(10),
Info VARCHAR(10),
Date DATETIME
)
INSERT INTO @Table SELECT 'R','North','AAA','2010-2-14'
INSERT INTO @Table SELECT 'R','North','AAA','2010-2-24'
INSERT INTO @Table SELECT 'T','North','AAA','2010-2-4'
INSERT INTO @Table SELECT 'R','South','AAA','2010-2-23'
INSERT INTO @Table SELECT 'T','South','AAA','2010-2-14'
INSERT INTO @Table SELECT 'R','EAST',' AAA','2010-2-22'
INSERT INTO @Table SELECT 'T','EAST',' AAA','2010-2-11'
INSERT INTO @Table SELECT 'T','EAST',' AAA','2010-2-1'
INSERT INTO @Table SELECT 'T','EAST',' AAA','2010-2-14'
INSERT INTO @Table SELECT 'R','WEST',' AAA','2010-2-28'
;WITH Dates AS(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Zone ORDER BY Date) ROWID
FROM @Table
WHERE Flag = 'R'
AND Date > GETDATE()
)
SELECT *
FROM Dates
WHERE ROWID = 1
如果您不能使用ROW_NUMBER你可以嘗試
SELECT t.*
FROM (
SELECT Zone,
MAX(Date) MaxDate
FROM @Table
WHERE Flag = 'R'
AND Date > GETDATE()
GROUP BY Zone
) Dates INNER JOIN
@Table t ON Dates.Zone = t.Zone and Dates.MaxDate = t.Date
但是,這將不排除重複...
謝謝,我稍後再試一次。 – 2010-02-21 08:12:24