计算 SQL 中选定 ID 的列总和
Posted
技术标签:
【中文标题】计算 SQL 中选定 ID 的列总和【英文标题】:Calculate sum of column for selected Ids in SQL 【发布时间】:2012-04-23 10:35:54 【问题描述】:这些是我的桌子:
会员:Id, Points
购物车注册:Id, Member_Id, CartId, RegisterDate, Point
SelectetMembers: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
之类的东西你有什么建议?
【问题讨论】:
我认为应该是WHERE [CR].[Member_Id] = [Member].Id
。
@NikolaMarkovinović 谢谢你的答案是正确的,你能把它写成答案吗,我可以接受。
【参考方案1】:
您可以使用 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
【讨论】:
【参考方案2】:@marc_s's solution 的变体,基本相同,只是语法略有不同:
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
【讨论】:
【参考方案3】:检查这个:
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 )
【讨论】:
以上是关于计算 SQL 中选定 ID 的列总和的主要内容,如果未能解决你的问题,请参考以下文章