2

让我描述一下整个情况:我有下面两张表。需要使用一些 Aggregate 子句来更新表中MaxTestCasesExecutedBySingleUser和表TotalTestCasesExecutedByAllUser中的值Module

CREATE TABLE [dbo].[Module](
    [ProjectID] [int] NOT NULL,
    [ModuleID] [int] NOT NULL,
    [ModuleName] [nvarchar](100) NOT NULL,
    [MaxTestCasesExecutedBySingleUser] [int] NULL,
    [TotalTestCasesExecutedByAllUser] [int] NULL,
    PRIMARY KEY ([ProjectID],[ModuleID]))

CREATE TABLE [dbo].[ModuleMember](
    [ProjectID] [int] NOT NULL,
    [ModuleID] [int] NOT NULL,
    [SerialNo] [int] NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    PRIMARY KEY ([ProjectID],[ModuleID],[SerialNo]))

Insert Into Module Values (1,1,'Installation_Test',null,null)
Insert Into Module Values (1,2,'Server_Test',null,null)
Insert Into Module Values (1,3,'Client_Test',null,null)
Insert Into Module Values (1,4,'Security_Test',null,null)

Insert Into ModuleMember Values(1,1,0,'Jim')
Insert Into ModuleMember Values(1,1,1,'Bob')
Insert Into ModuleMember Values(1,2,0,'Jack')
Insert Into ModuleMember Values(1,2,1,'Steve')
Insert Into ModuleMember Values(1,2,2,'Roy')
Insert Into ModuleMember Values(1,2,3,'Jerry')
Insert Into ModuleMember Values(1,3,0,'Root')
Insert Into ModuleMember Values(1,3,1,'Tom')
Insert Into ModuleMember Values(1,4,0,'Evil')

还有另一个表值函数dbo.GetValue,它将Name(来自ModuleMember表)作为参数并以表的形式返回NameTestCasesExecutedByTheUser 。我需要更新Module表中的这两个值。

定义:

MaxTestCasesExecutedBySingleUser = 如果测试用例由模块中的成员执行,则最大数量

TotalTestCasesExecutedByAllUser = 模块中所有成员执行的测试用例总数。

我尝试了以下查询,但它抛出了错误:An aggregate may not appear in the set list of an UPDATE statement.

UPDATE M
SET 
M.MaxTestCasesExecutedBySingleUser = MAX(N.TestCasesExecutedByTheUser),
M.TotalTestCasesExecutedByAllUser = SUM(N.TestCasesExecutedByTheUser)
FROM Module M 
JOIN ModuleMember Mem ON (M.ProjectID = Mem.ProjectID AND M.ModuleID = Mem.ModuleID)
CROSS APPLY dbo.GetValue(Mem.Name) N
4

2 回答 2

4

解决方法有点冗长 - 您必须先获取聚合(例如在 CTE 中),然后更新目标表:

;WITH src AS
(
  SELECT 
    Mem.ProjectID,  
    Mem.ModuleID,
    mtc = MAX(N.TestCasesExecutedByTheUser),
    stc = SUM(N.TestCasesExecutedByTheUser)
  FROM dbo.ModuleMember AS Mem
  CROSS APPLY dbo.GetValue(Mem.Name) AS N
  GROUP BY Mem.ProjectID, Mem.ModuleID
)
UPDATE M
  SET M.MaxTestCasesExecutedBySingleUser = src.mtc,
      M.TotalTestCasesExecutedBySingleUser = src.stc
FROM dbo.Module AS M
INNER JOIN src 
ON M.ProjectID = src.ProjectID 
AND M.ModuleID = src.ModuleID;
于 2013-08-04T01:12:06.520 回答
2

我认为这是使用apply的完美案例

update Module set
    MaxTestCasesExecutedBySingleUser = C.maxtc,
    TotalTestCasesExecutedByAllUser = C.sumtc
from Module as M
    cross apply (
        select
            max(N.TestCasesExecutedByTheUser) as maxtc,
            sum(N.TestCasesExecutedByTheUser) as sumtc
        from ModuleMember as MM
            cross apply dbo.GetValue(MM.Name) as N
        where MM.ProjectID = M.ProjectID and MM.ModuleID = M.ModuleID
    ) as C
于 2013-08-04T06:44:19.137 回答