【发布时间】:2015-01-28 08:11:19
【问题描述】:
我这里有 4 个表格,我需要将表格中新输入的行值与另一行相乘,然后使用 CustomerId 找到总和:
客户表:
CustomerId Name EmailId
-------------------------
1 Paul r@r.com
2 John J@j.com
忠诚度积分表:
LoyaltyPointsId LoyaltyType Points
---------------------------------------
1 Registration 10
2 Loginstatus 1
3 Downloading 10
4 Redemming 1
5 Sharing 20
6 Refer 10
忠诚度详情表:
LoyaltyDetailsId LoyaltyPointsId CustomerId Dates
-------------------------------------------------
1 1 1 2015-01-22
2 2 1 2015-01-22
3 3 2 2015-01-22
4 3 1 2015-01-22
5 4 1 2015-01-22
6 4 1 2015-01-24
7 5 1 2015-01-24
此查询适用于每个LoyaltyType 的总和
SELECT
LoayaltyPointsTable.LoyaltyType,
COUNT(CustomerTable.CustomerId) AS UserActions,
SUM(LoayaltyPointsTable.Points) AS TotalPoints
FROM
LoayaltyPointsTable
JOIN
LoyaltyDetailsTable ON LoayaltyPointsTable.LoyaltyPointsId = LoyaltyDetailsTable.LoyaltyPointsId
JOIN
CustomerTable ON CustomerTable.CustomerId = LoyaltyDetailsTable.CustomerId
WHERE
CustomerTable.CustomerId = 1
GROUP BY
LoyaltyDetailsTable.CustomerId ,LoayaltyPointsTable.LoyaltyType
在RedeemPointsTable 下方创建与LoyaltyPointTable 中的行兑换相关:
兑换积分表:
RedeemPointsId CustomerId ShopName BillNo Amount
------------------------------------------------
1 1 Mall x 4757 100
3 1 Mall y SH43 50
4 1 Mall x 7743 10
6 1 Mall x s34a 60
我的期望是在计算总和之前,我希望将 LoyaltyPointTable 中的 Redeeming 中的 Amount 和 (100+50+10+60) * 1 列与每个 CustomerId 的总分相加
预期输出
LoyaltyType UserActions TotalPoints
-------------------------------------
Downloading 1 10
Loginstatus 1 1
Redemming 4 (100+50+10+60)*1(here using Amount in RedeemPointsTable)
Refer 1 10
Registration 1 10
Sharing 1 20
用户操作计数为 4,它基于他在RedeemPointsTable 中输入的Amount
在RedeemPointsTable中添加外键列是否需要进行更改,或者您能指出我的错误吗?
任何帮助都会很棒。
【问题讨论】:
标签: sql sql-server sum multiplication