规范化sql查询以根据条件返回SUM列

时间:2018-03-05 06:20:01

标签: sql-server sql-server-2008

对于下面的查询,我需要根据以下检查显示结果 qs13_b_BuildingInsuranceAmt总和应该基于以下条件发生。

AND SP.Data.value('(/*/Answers/AnswersList/Entry[@key="as22_RightOfPledgeNum"]/value)[1]', 'nvarchar(max)') = @AS22_RightOfPledgeNum
    AND SP.Data.value('(/*/Answers/AnswersList/Entry[@key="as18_BuildingRightOfPledge"]/value)[1]', 'bit') = 1

类似于下面的其他列;

qs14_OutdoorEquipment --> AS19_OutdoorEquipmentRightOfPledge
qs15_EquipmentsMachinery --> AS20_EquipmentsMachineryRightOfPledge
qs16_MerchandiseProduct --> AS21_MerchandiseProductRightOfPledge

下面是具有完整详细信息的结果查询。我需要根据上述条件对各个列求和。

DECLARE @LocationSubjectData table (
        ProposalId uniqueidentifier
        ,QL4_Num int
        ,SumOfQS13AndQS14 decimal
        ,SumOfQS15 decimal
        ,SumOfQS16 decimal
        ,SumOfQS13bAndQS14b decimal
        ,SumOfQS15b decimal
        ,SumOfQS16b decimal
    )
    INSERT INTO @LocationSubjectData
    SELECT
        Loc.ProposalId
        ,Loc.QL4_Num
        ,SUM(ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs13_Building"]/value)[1]', 'decimal'), 0) + ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs14_OutdoorEquipment"]/value)[1]', 'decimal'), 0))
        ,SUM(ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs15_EquipmentsMachinery"]/value)[1]', 'decimal'), 0))
        ,SUM(ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs16_MerchandiseProduct"]/value)[1]', 'decimal'), 0))
        ,SUM(ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs13_b_BuildingInsuranceAmt"]/value)[1]', 'decimal'), 0) + ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs14_b_OutdoorEquipmentInsuranceAmt"]/value)[1]', 'decimal'), 0))
        ,SUM(ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs15_b_EquipmentsMachineryInsuranceAmt"]/value)[1]', 'decimal'), 0))
        ,SUM(ISNULL(SP.Data.value('(/*/Answers/AnswersList/Entry[@key="qs16_b_MerchandiseProductInsuranceAmt"]/value)[1]', 'decimal'), 0))
    FROM @Locations Loc
    INNER JOIN SubProposal SP ON SP.MasterProposalId = Loc.ProposalId
    WHERE SP.EndEffectiveDate = @EndEffectiveDate
    AND ISNULL(SP.Data.value('(/*/IsRemovedByEndorsement)[1]', 'bit'), 0) = 0
    GROUP BY Loc.ProposalId, Loc.QL4_Num

0 个答案:

没有答案