6

这些是我的表:

  • 会员Id, Points
  • 购物车注册Id, Member_Id, CartId, RegisterDate, Point
  • 选择成员Id, Member_Id

会员可以在购物车中注册CartRegister,并且在Member.Points会员赚取的所有积分中必须计算并插入。所以我需要计算每个点的所有点SelectedMembers并更新Member表格,但我不知道如何实现它。

以下脚本在我的脑海中:

UPDATE [Member]
   SET [Points]=
    (
       SELECT SUM([CR].[Point]) AS [AllPoints]
       FROM  [CartRegister] AS [CR] 
       WHERE [CR].[Member_Id] = --???

    )
    WHERE [Members].[Member].[Id] IN  ( SELECT Member_Id From SelectedMembers  )

所以我很困惑Select Sum(Point)如果我使用where 子句是什么

        WHERE [CR].[Member_Id] IN ( Select Member_Id From SelectedMembers  )

那么所有会员的总和与所有会员积分的总和相同,也许我需要类似foreach你的建议是什么?

4

3 回答 3

7

您可以使用 CTE(通用表表达式)首先计算每个成员的点数,然后使用该信息更新Members表:

-- this CTE takes all selected members, and calculates their total of points
;WITH MemberPoints AS
(
   SELECT 
       Member_ID,
       AllPoints = SUM(Point)
   FROM  
       CartRegister
   WHERE
       Member_ID IN (SELECT ID FROM SelectedMembers)
   GROUP BY 
       Member_ID
)
UPDATE dbo.Member  
SET Points = mp.AllPoints
FROM MemberPoints mp
WHERE dbo.Member.Member_ID = mp.Member_ID
于 2012-04-23T10:42:13.317 回答
0

@marc_s 解决方案的一个变体,基本相同,只是使用了稍微不同的语法:

WITH aggregated AS (
  SELECT
    *,
    AllPoints = SUM(Point) OVER (PARTITION BY Member_ID)
  FROM CartRegister
  WHERE Member_ID IN (SELECT ID FROM SelectedMembers)
)
UPDATE aggregated
SET Points = AllPoints
于 2012-04-23T11:07:23.920 回答
0

检查这个:

UPDATE [Member]
SET [Points]=
(
   SELECT SUM([CR].[Point]) AS [AllPoints]
   FROM  [CartRegister] AS [CR] 
   WHERE [CR].[Member_Id] = [Member].[Id]

)
WHERE [Members].[Member].[Id] IN  ( SELECT Member_Id From SelectedMembers  )
于 2012-04-23T11:29:34.633 回答