我遇到了问题,我无法弄清楚如何修复此查询。我有一个临时表,其中一列应该包含另一列的计算值除以该列的组的总和。我不知道如何写这个以避免错误。
Declare @Temp Table
(
ZipCode char(5) Not Null,
StateFacilityId varchar (50) Not Null,
Cnt int Not Null,
MarketShare float,
Row int Not Null,
Primary Key Clustered (ZipCode, StateFacilityId)
);
Insert Into @Temp (ZipCode, StateFacilityId, Cnt, Row)
Select d.ZipCode, d.StateFacilityId, Cnt = COUNT(*), Row = ROW_NUMBER()OVER(PARTITION BY ZipCode ORDER BY Count(*) DESC)
From [MarketShareIQData].[dbo].[tblServicesDetail] d
Group By d.ZipCode, d.StateFacilityId
;
Update @Temp
Set MarketShare =(h.Cnt/(
Select SUM(h.Cnt)
From @Temp h
Group By ZipCode
))
From @Temp h
答案 0 :(得分:1)
group by
每组会返回一行。我猜你正在寻找具有匹配邮政编码的单一组。你可以这样做:
update h
set MarketShare = h.Cnt /
(
select sum(h2.Cnt)
from @Temp h2
where h2.ZipCode = h.ZipCode
)
from @Temp h