我有以下数据。
我需要查询数据,以便我只获得以下记录。
我需要基于DateApplication的唯一记录。如下所示。
有人可以告诉我如何在SQL Server 2008中执行此操作吗?
答案 0 :(得分:3)
您可以在此处使用row_number()
功能:
select
name,
email,
dateapplication,
description
from
(
select *, row_number() over (partition by email order by dateapplication desc) as row_num
from YourTable
)a
where row_num = 1
答案 1 :(得分:2)
SELECT Name, email, MAX(DateApplication) As DateApplication,
(SELECT TOP 1 description
FROM tbl As tbl1
where tbl1.Email = tbl.Email AND tbl1.DateApplication = MAX(tbl.DateApplication))
) As description
from tbl
GROUP BY Name, email
答案 2 :(得分:2)
皮肤猫的方法不止一种,但通常情况下,你有一个子查询返回每个名字及其最新日期,然后用原始表格加入。
使用WITH语句
;WITH q AS (
SELECT Name, DateApplication = MAX(DateApplication)
FROM YourData
GROUP BY
Name
)
SELECT Name
, Email
, DateApplication
, Description
FROM YourTable yt
INNER JOIN q ON q.Name = yt.Name
AND q.DateApplication = yt.DateApplication
使用内部联接
SELECT Name
, Email
, DateApplication
, Description
FROM YourTable yt
INNER JOIN (
SELECT Name, DateApplication = MAX(DateApplication)
FROM YourData
GROUP BY
Name
) q ON q.Name = yt.Name
AND q.DateApplication = yt.DateApplication
请注意,在每个示例中,我都假设组合Name, DateApplication
是唯一的。
答案 3 :(得分:2)
你可以试试这个
SELECT Name, Email, DateApplication, Description
FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY Name ORDER BY DateApplication DESC) RowNumber,
Name, Email, DateApplication, Description
FROM YourTableName)
WHERE RowNumber = 1
希望这有帮助
答案 4 :(得分:1)
假设您想要最后一个条目,您可以这样做:
SELECT t1.Name, t1.Email, t1.DateApplication, t1.Description
FROM tablename t1
WHERE t1.DateApplication =
(SELECT MAX(t2.DateApplication)
FROM tablename t2
WHERE t2.Name = t1.Name AND t2.Email = t1.Email)