0

我遇到了问题,我不知道如何解决此查询。我有一个临时表,其中一列应包含另一列的计算值除以该列的组总和。我不知道如何写这个,以避免错误。

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
4

1 回答 1

1

Agroup by将返回每组一行。我猜您正在寻找具有匹配邮政编码的单个组。你可以这样做:

update h
set     MarketShare = h.Cnt /
        (
        select  sum(h2.Cnt)
        from    @Temp h2
        where   h2.ZipCode = h.ZipCode
        )
from    @Temp h
于 2012-06-18T17:04:01.607 回答