我有以下查询,它返回一个项目的多个结果。我只想获得最新日期(最新)的1项。我目前正在获得每个有条目的日期的结果。
SELECT DISTINCT
[a].[Name]
, [a].[IsGhostConvey]
, [b].[AttorneyName]
, [b].[IsGhostConveyAttorney]
, [c].[InstitutionID]
, [f].[Base_CreatedDate] AS 'DateLatestAccountOpened'
FROM
[Intermediary] [a]
INNER JOIN
[Attorney] [b] ON [a].[Name] = [b].[AttorneyName]
INNER JOIN
[IntermediaryInstitution] [c] ON [c].[IntermediaryID] = [a].[ID]
INNER JOIN
[IntermediaryBranch] [d] ON [d].[IntermediaryID] = [a].[Id]
INNER JOIN
[Matter] [e] ON [e].[BranchID] = [d].[Id]
INNER JOIN
[Account] [f] ON [f].[MatterID] = [e].[ID]
ORDER BY
[a].[Name], [f].[Base_CreatedDate] DESC;
我想我错过了WHERE
,GROUP BY
或HAVING
声明。
我的结果如下:
Name IsGhostConvey AttorneyName IsGhostConveyAttorney InstitutionID DateLatestAccountOpened
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2017-10-05 08:46:47.573
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2017-05-25 09:00:24.853
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2017-03-03 10:07:01.753
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2016-12-15 08:47:59.393
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2016-11-09 14:55:29.763
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2016-11-09 14:54:11.877
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2016-05-30 08:43:47.993
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 NULL
Adriaan Booyens Attorneys 1 Adriaan Booyens Attorneys 1 1 2018-02-05 12:25:17.233
Adriaan Booyens Attorneys 1 Adriaan Booyens Attorneys 1 1 2017-06-14 10:25:42.687
但我想这样:
Name IsGhostConvey AttorneyName IsGhostConveyAttorney InstitutionID DateLatestAccountOpened
Adlam Attorneys - Benoni 1 Adlam Attorneys - Benoni 1 2 2017-10-05 08:46:47.573
Adriaan Booyens Attorneys 1 Adriaan Booyens Attorneys 1 1 2018-02-05 12:25:17.233
答案 0 :(得分:3)
您可以使用row_number()
来执行如下复杂查询:
with t as (
SELECT a.Name, a.IsGhostConvey, b.AttorneyName, b.IsGhostConveyAttorney, c.InstitutionID, f.Base_CreatedDate AS 'DateLatestAccountOpened'
FROM Intermediary a
INNER JOIN Attorney b
ON a.Name = b.AttorneyName
INNER JOIN IntermediaryInstitution c
ON c.IntermediaryID = a.ID
INNER JOIN IntermediaryBranch d
ON d.IntermediaryID = a.Id
INNER JOIN Matter e
ON e.BranchID = d.Id
INNER JOIN Account f
ON f.MatterID = e.ID
)
select t.*
from (select t.*,
row_number() over (partition by name order by DateLatestAccountOpened desc) as seqnum
from t
) t
where seqnum = 1
order by Name, Base_CreatedDate DESC;
答案 1 :(得分:-1)
您可以使用
GROUP BY (name)
为每个名称获得1个结果