最大日期sql server

时间:2014-05-28 19:42:09

标签: sql-server

我有一个包含数据的表格,我正在尝试查找最长日期验证

Create table staging(ID varchar(5) not null, Name varchar(200) not null, dateverified datetime not null,dateinserted datetime not null)
ID,Name,DateVerified,DateInserted
42851775,384,2014-05-24 08:48:20.000,2014-05-28 14:28:10.000
42851775,384,2014-05-28 13:13:07.000,2014-05-28 14:36:12.000
42851775,a1d,2014-05-28 09:17:22.000,2014-05-28 14:36:12.000
42851775,a1d,2014-05-28 09:17:22.000,2014-05-28 14:28:10.000
42851775,a1d,2014-05-28 09:17:22.000,2014-05-28 14:29:08.000
42851775,bc5,2014-05-28 09:17:21.000,2014-05-28 14:29:08.000
42851775,bc5,2014-05-28 09:17:21.000,2014-05-28 14:28:10.000
42851775,bc5,2014-05-28 09:17:21.000,2014-05-28 14:36:12.000

我想显示每个keyid的最大日期验证,即。

42851775,384,2014-05-28 13:13:07.000,2014-05-28 14:36:12.000
42851775,a1d,2014-05-28 09:17:22.000,2014-05-28 14:36:12.000
42851775,bc5,2014-05-28 09:17:21.000,2014-05-28 14:29:08.000

 SELECT i.[ID],i.name,i.dateinserted,r.maxdate
    FROM (select id,name,max(dateverified) as maxdate from 
   [dbo].[staging] where id=42851775 group by id,name) r 
  inner join 
 [dbo].[staging] i 
  on r.id=i.id and r.jobpostingurl=i.jobpostingurl and r.maxdate=i.dateverified
   group by i.id,i.jobpostingurl,r.maxdate

我收到错误,dateinserted无效,因为它不包含在group by子句中。但如果我在group by子句中添加它,我将得到所有8条记录。如何处理?

由于 [R

2 个答案:

答案 0 :(得分:3)

    SELECT
        KeyID,
        MAX(yourDate)
   FROM
        Staging
    GROUP BY
        KeyID

如果您想要其他信息,请将其加入另一个表格,例如:

SELECT
     b.KeyID,
     a.dateinserted,
     b.TheDate
FROM YourTable a
INNER JOIN
(
    SELECT
        KeyID,
        MAX(yourDate) AS TheDate
    FROM 
        Staging
    GROUP BY
        KeyID
) b
ON
b.KeyID = a.KeyID

答案 1 :(得分:1)

如果您需要获取dateinserted,您可以使用cte并将其连接回原始表:

WITH    cte
          AS ( SELECT   [ID] ,
                        name ,
                        MAX(dateverified) AS dateverified
               FROM     [dbo].[staging]
               GROUP BY ID ,
                        name
             )
    SELECT  cte.[ID] ,
            cte.NAME ,
            cte.dateverified ,
            s.Dateinserted
    FROM    cte
            INNER JOIN dbo.staging s ON cte.[ID] = s.[ID]
                                        AND cte.NAME = s.NAME
                                        AND cte.dateverified = s.dateverified