查询具有最大日期.... sorta的组的多个记录

时间:2013-09-16 18:53:31

标签: sql sql-server sql-server-2008 tsql

示例代码:

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 /名称的数据(最大(日期))(如果在同一日期/时间处理它们,可以有多个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 /名称/日期的记录。

谢谢

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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;