简体   繁体   中英

How to Select Distinct Name based on LastCreatedDate in SQL

I have sample table with columns:

ID(guid)                                 Name        CreatedDate

B27EB95B-B219-46BD-9E72-A378B3E7FED0    A       2005-11-20 22:49:46.000
33D43825-918D-4DC0-874A-53670563EA03    A       2009-10-03 10:34:00.000
28F26DA6-B144-4C0C-AC2F-4DDD2D74357E    B       2011-03-23 08:08:39.000
1491D95F-BA58-41EE-8982-B713DE9DECD7    C       2006-01-18 14:53:12.000
FD25C05D-0C1A-4314-BCA7-F4F33B0E890D    C       2006-10-05 14:25:58.000
F4256300-CAA6-4E80-8D1B-B89273274088    D       2008-03-12 08:56:32.000

That Supposed to be my OledbDatasource on SSIS.

Now problem is i need to get the distinct Name having the last createdDate and its Id in sql.

This is the output result:

ID(guid)                                 Name        CreatedDate

33D43825-918D-4DC0-874A-53670563EA03    A       2009-10-03 10:34:00.000
28F26DA6-B144-4C0C-AC2F-4DDD2D74357E    B       2011-03-23 08:08:39.000
047ED9C3-DF92-45D5-B295-EE52184116FB    C           2006-10-05 14:23:40.000
F4256300-CAA6-4E80-8D1B-B89273274088    D       2008-03-12 08:56:32.000

Thanks in Regards

If you are on SQL Server 2005 or later, you can use ranking and a CTE :

WITH ranked AS (
  SELECT
    ID, Name, CreatedDate,
    rn = ROW_NUMBER() OVER (PARTITION BY Name ORDER BY CreatedDate DESC)
  FROM atable
)
SELECT
  ID,
  Name,
  CreatedDate
FROM ranked
WHERE rn = 1
SELECT ID, Name, CreatedDate
FROM table JOIN
  (SELECT MAX(CreatedDate) CreatedDate, Name FROM table GROUP BY Name) max_date
USING (Name, CreatedDate)

(Change table to the actual name of the table.)

For SQLServer do:

SELECT table.ID, table.Name, table.CreatedDate
FROM table JOIN
  (SELECT MAX(CreatedDate) CreatedDate, Name FROM table GROUP BY Name) max_date
ON table.Name = max_date.name AND table.CreatedDate = max_date.CreatedDate

Try this out

SELECT myTable.Id, myTable.Name, myTable.CreatedDate
FROM table as myTable
INNER JOIN (SELECT Name, MAX(CreatedDate) AS MaxDate FROM table GROUP BY Name) 
    AS MaxRecord ON MaxRecord.Name = myTable.Name 
                AND MaxRecord.MaxDate= myTable.CreatedDate

This will produce the result you want on SQL Server:

select distinct x.ID, x.Name, x.CreatedDate
from table t
    cross apply (
        select top 1 ID, Name, CreatedDate
        from table t1 
        where t1.Name = t.Name
        order by CreatedDate desc
    ) x
order by x.Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM