对于Azure搜索,我们需要在视图中有一个高水印列。该视图汇总了许多其他表中的信息,并且其中任何一个表中有更新时,都需要增加高水位标记。在所有表中我们都已经具有“创建和更新”属性,该字段可用作水印,这意味着我们只需在任何相关的“创建”或“更新”列中找到最大值。
在数据库中,雇主表与许多属性具有一对多关系,在此示例中,两个是相关的:payrollSoftware表和雇佣关系。雇主只有一个有效的薪资软件包,因此我们可以通过获取最新的信息将这种多对一关系简化为一对一关系。由于法规,我们仍然需要保留旧的。
对于这种一对一的关系,我们使用以下代码从不同的列中获取最大值:
(SELECT MAX(newest)
FROM (VALUES (employer.Updated), (payroll.Updated), (payroll.Created), (employer.Created)) as value(newest))
as UpdatedAt
遗憾的是,这不适用于一对多关系。第一个直觉是在值中使用(Max(employments.Created))
,但这是不允许的。我尝试了一个子查询,但无法弄清楚如何将结果放入VALUES中。
完整查询:
CREATE VIEW FullEmployer AS
SELECT employer.Id, employer.Name as EmployerName, employer.Active, COUNT(employments.CustomerId) as Employees, payroll.Name as PayrollName,
employer.PhoneNumber, employer.City, employer.Email,
(SELECT MAX(newest)
FROM (VALUES (employer.Updated), (payroll.Updated), (payroll.Created), (employer.Created)) as value(newest)) as UpdatedAt
FROM DB.Employers AS employer
LEFT OUTER JOIN DB.PayrollSoftware payroll ON employer.PayrollSoftwareId = payroll.Id
LEFT OUTER JOIN DB.PayrollSoftware payroll2 On employer.PayrollSoftwareId = payroll2.Id AND
(payroll.Created < payroll2.Created OR (payroll.Created = payroll2.Created AND payroll.Id < payroll2.Id))
LEFT OUTER JOIN DB.Employments employments ON employer.Id = employments.EmployerId
WHERE payroll2.Id IS NULL AND
employments.Active = 1
group by employer.Id, payroll.Name, employer.Name, employer.Active, employer.Updated, payroll.Updated, payroll.Created,
employer.Created, employer.PhoneNumber, employer.City, employer.Email
问题:还有更好的方法吗?如果没有,我们如何获得雇主相关实体的任何“已更新”或“已创建”列的MAX值?