0

示例代码:

DECLARE @TABLE TABLE (ID int, Name varchar(50), Date Datetime2)

INSERT INTO @TABLE (ID, Name, Date)
SELECT 1, 'abc', GETDATE()
UNION ALL
SELECT 1, 'def', GETDATE()
UNION ALL
SELECT 1, 'hij', GETDATE()
UNION ALL
SELECT 1, 'abc', GETDATE()-2
UNION ALL
SELECT 1, 'def', GETDATE()-2
UNION ALL
SELECT 1, 'hij', GETDATE()-2
UNION ALL
SELECT 1, 'abc', GETDATE()-4
UNION ALL
SELECT 1, 'def', GETDATE()-4
UNION ALL
SELECT 1, 'hij', GETDATE()-4
UNION ALL
SELECT 2, 'abc', GETDATE()-1
UNION ALL
SELECT 2, 'def', GETDATE()-1
UNION ALL
SELECT 2, 'hij', GETDATE()-1
UNION ALL
SELECT 2, 'abc', GETDATE()-3
UNION ALL
SELECT 2, 'def', GETDATE()-3
UNION ALL
SELECT 2, 'hij', GETDATE()-3
UNION ALL
SELECT 2, 'abc', GETDATE()-4
UNION ALL
SELECT 2, 'def', GETDATE()-4
UNION ALL
SELECT 2, 'hij', GETDATE()-4
UNION ALL
SELECT 3, 'abc', GETDATE()+2
UNION ALL
SELECT 3, 'def', GETDATE()+2
UNION ALL
SELECT 3, 'hij', GETDATE()+2
UNION ALL
SELECT 3, 'abc', GETDATE()-4
UNION ALL
SELECT 3, 'def', GETDATE()-4
UNION ALL
SELECT 3, 'hij', GETDATE()-4
UNION ALL
SELECT 3, 'abc', GETDATE()-5
UNION ALL   
SELECT 3, 'def', GETDATE()-5
UNION ALL
SELECT 3, 'hij', GETDATE()-5
UNION ALL
SELECT 4, 'abc', GETDATE()+1
UNION ALL
SELECT 4, 'def', GETDATE()+1
UNION ALL
SELECT 4, 'hij', GETDATE()+1
UNION ALL
SELECT 4, 'abc', GETDATE()-4
UNION ALL
SELECT 4, 'def', GETDATE()-4
UNION ALL
SELECT 4, 'hij', GETDATE()-4
UNION ALL
SELECT 4, 'abc', GETDATE()-5
UNION ALL   
SELECT 4, 'def', GETDATE()-5
UNION ALL
SELECT 4, 'hij', GETDATE()-5

SELECT * FROM @TABLE

我想要的数据输出反映了以下记录的输出

3   abc 2013-09-18 
3   def 2013-09-18 
3   hij 2013-09-18 

描述:我想查询最近处理的 ID/Name 的数据(Max(Date))(如果在同一日期/时间处理,可以有多个 ID)

我的尝试...

SELECT  DISTINCT A.*, B.My_Rank
FROM    @TABLE A
        INNER JOIN
        (
            SELECT  DISTINCT ID, Name, CONVERT(varchar(8), Date, 101) AS Date, RANK() OVER (PARTITION BY ID, Name ORDER BY CONVERT(varchar(8), Date, 101) DESC) My_Rank, MAX(CONVERT(varchar(8), Date, 101)) OVER (partition by ID, Name) Max_Date
            FROM    @TABLE
            GROUP   BY ID, Name, CONVERT(varchar(8), Date, 101)
        ) B 
ON  A.ID = B.ID AND CONVERT(varchar(8), A.Date, 101) = B.Max_Date
WHERE My_Rank = 1

显然,这个逻辑是行不通的。“我想根据最新处理的 ID/姓名获取 ID/姓名/日期的记录。

谢谢

4

2 回答 2

3

你很接近,但你不必加入(你可能不想要 PARTITION BY id:

SELECT *
FROM
 (
   SELECT  ID, Name, Date, 
      RANK() OVER (ORDER BY CAST(Date AS DATE) DESC) My_Rank
   FROM @TABLE
 ) dt
WHERE My_rank = 1      

AFAIK SS2008 支持 CAST(x AS DATE)

于 2013-09-16T19:20:27.347 回答
1

您想max()partition by子句一起使用:

SELECT  * 
FROM (select a.*,
             max("date") over (partition by id) as maxdate
      from @TABLE A
     ) a
where "date" = maxdate;

这可以返回多行。如果你只有一个,即使有关系,也可以使用row_number()

SELECT  * 
FROM (select a.*,
             row_number() over (partition by id order by "date" desc) as seqnum
      from @TABLE A
     ) a
where seqnum = 1;
于 2013-09-16T18:57:36.163 回答