根据另一个 table 中的记录数更新 table

Update table based on a count of records in another table

我需要帮助根据另一个 table 中匹配记录的计数来更新 table 中的列。

我有 3 个 tables:

[EventDescriptions]
EventID, Description, StartDateTime

[EventEntries]
EntryID, EmployeeKey, EventID, Priority

[EventWinners]
WinnerID, EventID, EmployeeKey

抽取获胜者时,我需要更新 EventEntries table 中的优先级列,仅适用于从今天开始的未来事件以及在 EventWinners 中找到员工的行 table 从今天算起过去90天。优先级列为尚未赢得比赛的人提供了赢得下一场比赛的更高机会,优先级 1 与优先级 2 或 3。

使用 CTE 或子查询获取 EmployeeKey 最近事件的获胜者计数。接下来,使用 EventEntries 加入此 CTE,并仅将 EventEntries 过滤到未来的事件。您现在将获得足够的上下文信息来根据您的规则设置 Priority

--!!! Please backup your data before running the update, or do it as a transaction and test the result before committing. !!!

WITH [recent-event-winner-counts] AS (
    SELECT [EmployeeKey], COUNT(*) AS [Occurrences]
    FROM [EventWinners] AS [w]
    INNER JOIN [EventDescriptions] AS [d]
    ON [w].[EventID] = [d].[EventID]
    WHERE [StartDateTime] BETWEEN DATEADD(DAY, -90, GETDATE()) AND GETDATE()
    GROUP BY [EmployeeKey]
)
UPDATE [e]; -- <- remove this semicolon when you're ready to run this
SET Priority = CASE
        WHEN [Occurrences] IS NULL THEN 1
        WHEN [Occurrences] = 1 THEN 2
        WHEN [Occurrences] >= 2 THEN 3
        ELSE Priority -- leave unchanged
    END
FROM [EventEntries] AS [e]
INNER JOIN [EventDescriptions] AS [d]
ON [e].[EventID] = [d].[EventID]
-- left join as we don't care about EmployeeKeys exclusively in EventWinners
LEFT JOIN [recent-event-winner-counts] AS [r]
ON [e].[EmployeeKey] = [r].[EmployeeKey]
WHERE [d].[StartDateTime] > GETDATE(); -- future events only