我有两个表,表a和表b。
表a设置为......
用户
Id ... InspectStat PurchaseStat SoldStat POSStat
------------------------------------------------------------
1
2
3
属性
UserId ... Stage
---------------------------------------------------
1 Inspect
3 Purchase
1 Sold
2 POS
我正在尝试每小时写一份工作,计算每个阶段每个用户总属性的百分比。所以例如,最终结果应该是这样的(假设只有这4个属性)
Id ... InspectStat PurchaseStat SoldStat POSStat
------------------------------------------------------------
1 .5 0 .5 0
2 0 0 0 1.0
3 0 1.0 0 0
我试过了
ALTER PROCEDURE [dbo].[StatCounter]
AS
DECLARE @PropertyCount as float
BEGIN
set @PropertyCount = (select count(AcquisitionAssociateId) from [dbo].[Properties], [dbo].[Users]
WHERE
[dbo].[Users].Id = [dbo].[Properties].AcquisitionAssociateId)
update [dbo].[Users]
set [dbo].[Users].PurchaseStat = ((select count (AcquisitionAssociateId) from [dbo].[Properties]
WHERE
[dbo].[Users].Id = [dbo].[Properties].AcquisitionAssociateId
and
[dbo].[Properties].Stage = 'Purchase') / @PropertyCount)
...Repeat for 3 other stages
这个方法正确地计算了每个阶段中的属性数量,但是在执行它之后,我意识到它实际上在做的是计算用户分配给它们的属性的数量,而不是得到一个明确的计数单个用户实际拥有多少属性。我正在学习SQL,所以非常感谢帮助。
答案 0 :(得分:1)
这是一个支点的特例。以下使用avg()
进行计算。它为stat分配值“1”,平均值除以行上的总数:
select userid,
avg(case when Stage = 'Inspect' then 1.0 else 0.0 end) as InspectStat,
avg(case when Stage = 'Purchase' then 1.0 else 0.0 end) as PurchaseStat,
avg(case when Stage = 'Sold' then 1.0 else 0.0 end) as SoldStat,
avg(case when Stage = 'POS' then 1.0 else 0.0 end) as POSStat
from properties p
group by userid