根据辅助表中的行更新主表

时间:2009-10-19 18:41:43

标签: asp.net sql-server

我有一个员工抽奖类型的应用程序,表格如下:

Employee (ID, name, selectionCount)

Selections (employeeID, ipAddress)

现在我需要一个更新查询,它将计算每个employeeID的选择数(具有唯一的IP地址),并更新表Employee中的selectionCount列。

4 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

WITH SelectionCounts(EmployeeId, SelectionCount)
AS
(
    SELECT s.EmployeeId, COUNT(DISTINCT IpAddress) AS SelectionCount
    FROM Selections s
    GROUP BY s.EmployeeId
)
UPDATE Employee
SET SelectionCount = sc.SelectionCount
FROM SelectionCounts sc
WHERE ID = sc.EmployeeId

没有测试它,因此语法可能不完全正确。

答案 1 :(得分:1)

update Employee
set selectionCount = (select count(distinct ipAddress) 
                        from Selections 
                       where Selections.emmployeeID = Employee.ID)

答案 2 :(得分:1)

接受najmeddine解决方案,您可以将该代码放入SQL Server中Selections表的插入和/或更新触发器中:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER UpdateSelectionCount ON Selections
    AFTER UPDATE, INSERT
AS
BEGIN
    SET NOCOUNT ON

    UPDATE
        Employee
    SET
        selectionCount = (SELECT
                              COUNT(DISTINCT ipAddress)
                          FROM
                              Selections
                          WHERE
                              Selections.EmployeeID = Employee.ID)

END
GO

答案 3 :(得分:0)

不是SQL Server专家,但这样的事情应该有效:

update Employee a
   set selectionCount = (select count(*)
                           from Selections
                          where employeeID = a.ID)

顺便说一句,我认为你知道设计有些非规范化,在某些情况下这可能是不受欢迎的。