我需要通过名称的SQL查询到组,但返回等领域基于最新的条目(I need a sql query t

2019-10-16 14:06发布

我叫查询PhoneCallNotes一个表。 呼叫者名字,姓氏和DOB被记录为每个呼叫以及许多其它领域包括用于该呼叫(PhoneNoteID),但是呼叫者不唯一ID的唯一ID。 我的要求是返回调用者的同与PhoneNoteID等从他们最近的条目一并删除重复项。 我能得到我想要使用的姓名,出生日期和Max(CreatedOn)一组由用户的列表,但我怎么包括UNIQUEID(在结果中距离最近的?)

select  O.CallerFName,O.CallerLName,O.CallerDOB,Max(O.CreatedOn)
from [dbo].[PhoneCallNotes] as O
where O.CallerLName like 'Public'
group by O.CallerFName,O.CallerLName,O.CallerDOB order by Max(O.CreatedOn) 

结果:

John    Public  4/4/2001    4/6/12 16:42
Joe     Public  4/12/1988   4/6/12 16:52
John    Public  1/2/1950    4/6/12 17:01

谢谢

Answer 1:

假设集合[的FirstNameLastNameDateOfBirth ]是唯一的(#不寒而栗#),我认为以下应工作,在几乎每一个主要的RDBMS:

SELECT a.callerFName, a.callerLName, a.callerDOB, a.createdOn, a.phoneNoteId
FROM phoneCallNotes as a
LEFT JOIN phoneCallNotes as b
ON b.callerFName = a.callerFName
AND b.callerLName = a.callerLName
AND b.callerDOB = a.callerDOB
AND b.createdOn > a.createdOn
WHERE a.callerLName LIKE 'Public'
AND b.phoneNoteId IS NULL

基本上,询问正在寻找每一个电话呼叫音符一个特定名称/ DOB组合,那里是不是,最近更行( b为null)。 如果你有两行用相同的创建时间,你会得到重复行,虽然。



Answer 2:

你也可以写什么安德烈,如果你选择TOP(1)关系,并把ROW_NUMBER()的表达在ORDER BY子句中写的有些更紧凑:

SELECT TOP (1) WITH TIES
  CallerFName,
  CallerLName,
  CallerDOB,
  CreatedOn,
  PhoneNoteID
FROM [dbo].[PhoneCallNotes]
WHERE CallerLName = 'Public' 
ORDER BY ROW_NUMBER() OVER(
  PARTITION BY CallerFName, CallerLName, CallerDOB
  ORDER BY CreatedOn DESC
)

(顺便说一下,有没有理由使用像一个简单的字符串比较。)



Answer 3:

尝试类似的东西:

;WITH CTE AS (
    SELECT  
        O.CallerFName,
        O.CallerLName,
        O.CallerDOB,
        O.CreatedOn,
        PhoneNoteID,
        ROW_NUMBER() OVER(PARTITION BY O.CallerFName, O.CallerLName, O.CallerDOB ORDER BY O.CreatedOn DESC) AS rn
    FROM [dbo].[PhoneCallNotes] AS O 
    WHERE 
        O.CallerLName LIKE 'Public' 

)
SELECT 
    CallerFName,
    CallerLName,
    CallerDOB,
    CreatedOn,
    PhoneNoteID
FROM CTE
WHERE rn = 1
ORDER BY 
    CreatedOn 


文章来源: I need a sql query to group by name but return other fields based on the most recent entry