按sql server中的最新日期和更新值分组
我正在尝试编写一个sql查询,其中:按sql server中的最新日期和更新值分组,sql,sql-server,group-by,sql-update,Sql,Sql Server,Group By,Sql Update,我正在尝试编写一个sql查询,其中: 获取数据库中有多个条目(通过电子邮件)的客户以及具有最新更新密码日期的客户,我要将其ID(pli.ID)更新为电子邮件(pfd.TextValue) 我编写此查询是为了检索PasswordDate上具有最高值的用户: select pfd.TextValue as 'Email', MAX(pli.PasswordDate) as 'LastUpdatedPassword' from [Customers].[PersonFieldData] pfd
- 获取数据库中有多个条目(通过电子邮件)的客户以及具有最新更新密码日期的客户,我要将其ID(pli.ID)更新为电子邮件(pfd.TextValue)
select pfd.TextValue as 'Email', MAX(pli.PasswordDate) as 'LastUpdatedPassword'
from [Customers].[PersonFieldData] pfd
join (
select pfd.TextValue from [Customers].[PersonFieldData] pfd
where pfd.FieldDefinitionId = '_email'
group by pfd.TextValue
HAVING COUNT(*) > 1
) sub
on pfd.TextValue = sub.TextValue
join [Customers].[Person] p
on pfd.OwnerSystemId = p.SystemId
join [Security].[PasswordLoginInfo] pli
on pli.SystemId = p.SystemId
group by pfd.TextValue;
这是我为更新这些值而编写的查询(不起作用):
我收到错误消息:
无法在对象“Security.PasswordLoginInfo”中插入具有唯一索引“IX\u PasswordLoginInfo\u Id”的重复密钥行。
如何仅在“PasswordDate”上具有最高值的客户上执行此更新?将
Id
更新为textValue
一开始听起来是错误的。好吧,有时你不得不求助于听起来不太好的东西,因此解决由错误开始的东西引起的问题:)但是,我假设,你想要的是一个“可更新的CTE”。这是一次性的还是常规的任务?
update pli
set pli.Id = pfd.TextValue
from [Jollyroom7].[Customers].[PersonFieldData] pfd
join (
select pfd.TextValue from [Customers].[PersonFieldData] pfd
where pfd.FieldDefinitionId = '_email'
group by pfd.TextValue
HAVING COUNT(*) > 1
) sub
on pfd.TextValue = sub.TextValue
join [Customers].[Person] p
on pfd.OwnerSystemId = p.SystemId
join [Security].[PasswordLoginInfo] pli
on pli.SystemId = p.SystemId