2010-02-21 59 views
1

從一組獲得日期備案基地這裏是數據如何使用T-SQL

Flag  Zone   Info   Date 
R   North  AAA   2010-2-14 
R   North  AAA   2010-2-24 
T   North  AAA   2010-2-4 
R   South  AAA   2010-2-23 
T   South  AAA   2010-2-14 
R   EAST   AAA   2010-2-22 
T   EAST   AAA   2010-2-11 
T   EAST   AAA   2010-2-1 
T   EAST   AAA   2010-2-14 
R   WEST   AAA   2010-2-29 

這是在SQL Server中的表,現在我想從根據各組的記錄區域列。該記錄的標誌字段應該是R,並且日期應該是最近的並且在今天的日期之後。

最好的問候,

回答

3

使用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 

但是,這將不排除重複...

+0

謝謝,我稍後再試一次。 – 2010-02-21 08:12:24