【问题标题】:Update table based on a count of records in another table根据另一个表中的记录数更新表
【发布时间】:2023-04-08 17:31:01
【问题描述】:

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

我有 3 张桌子:

[EventDescriptions]
EventID, Description, StartDateTime

[EventEntries]
EntryID, EmployeeKey, EventID, Priority

[EventWinners]
WinnerID, EventID, EmployeeKey

抽出获胜者后,我需要仅更新 EventEntries 表中的 Priority 列,以更新从今天开始的未来事件,以及从今天起 90 天前在 EventWinners 表中找到员工的行。优先级列让没有赢得比赛的人有更高的机会赢得下一场比赛,即优先级 1 与优先级 2 或 3。

  • 设置 Priority = 1,其中 EmployeeKey 在 EventWinners 中找不到,其中 StartDateTime 是从今天起过去不超过 90 天的事件。
  • 设置优先级 = 2,其中 EmployeeKey 在 EventWinners 中仅找到 1 次,其中事件的 StartDateTime 距离今天不超过过去 90 天。
  • 在 EventWinners 中设置优先级 = 3,其中找到 EmployeeKey >= 2,其中事件的 StartDateTime 从今天开始不超过过去 90 天

【问题讨论】:

  • 澄清请求:在EventWinners 表中,对于给定的EventID,相同的EmployeeKey 可以出现多次吗?例如,(1, 1, 1), (2, 1, 1), (3, 1, 1) (WinnerID, EventID, EmployeeKey) 的元组。因此,这应该算作EmployeeKey=1 出现一次还是出现3 次?
  • 不,它不能。 EmployeeKey 对于 EventWinners 表中的每个 EventID 都是唯一的。但是,每个 EventID 都可能包含相同的 EmployeeKey。谢谢!

标签: sql sql-server sql-update


【解决方案1】:

使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多