在SQL Server XML列中汇总特定节点的所有实例

时间:2019-06-10 19:42:24

标签: sql-server xml xml-parsing

我有以下xml数据列:

<AccountingDetail>
    <DetailItems>
        <AccountingDetailItem>
            <Credit>25</Credit>
            <Debit>15100</Debit>
        </AccountingDetailItem>
        <AccountingDetailItem>
            <Credit>5</Credit>
            <Debit>150.66</Debit>
        </AccountingDetailItem>
    </DetailItems>
</AccountingDetail>

如何获得此列中所有贷方和借方的总和?实例的数量因行而异。

我希望总和(借方)= 15250.66&总(贷方)= 30

2 个答案:

答案 0 :(得分:0)

您可以使用CTE(公用表表达式)非常轻松地完成此操作-类似这样(假设我们的XML数据存储在@XmlData XML变量中):

-- define the CTE to extract the individual Credit and Debit values
;WITH RawXmlData (Credit, Debit) AS
(
    SELECT
        Credit = ISNULL(XC.value('(Credit)[1]', 'decimal(16,4)'), 0.0),
        Debit = ISNULL(XC.value('(Debit)[1]', 'decimal(16,4)'), 0.0)
    FROM
        @XmlData.nodes('/AccountingDetail/DetailItems/AccountingDetailItem') XT(XC)
)
-- now select from that CTE and sum up the values
SELECT
    SumCredit = SUM(Credit),
    SumDebit = SUM(Debit)
FROM
    RawXmlData

答案 1 :(得分:0)

这可以在XML / XQuery中解决,与创建派生集并在外部进行聚合相比,该XML应该表现得更好:

DECLARE @tbl TABLE(ID INT IDENTITY,YourXml XML);
INSERT INTO @tbl VALUES
(N'<AccountingDetail>
    <DetailItems>
        <AccountingDetailItem>
            <Credit>25</Credit>
            <Debit>15100</Debit>
        </AccountingDetailItem>
        <AccountingDetailItem>
            <Credit>5</Credit>
            <Debit>150.66</Debit>
        </AccountingDetailItem>
    </DetailItems>
</AccountingDetail>')
,('<AccountingDetail>
    <DetailItems>
        <AccountingDetailItem>
            <Credit>10</Credit>
            <Debit>20</Debit>
        </AccountingDetailItem>
        <AccountingDetailItem>
            <Credit>20</Credit>
            <Debit>40</Debit>
        </AccountingDetailItem>
        <AccountingDetailItem>
            <Credit>30</Credit>
            <Debit>60</Debit>
        </AccountingDetailItem>
    </DetailItems>
</AccountingDetail>');

SELECT t.YourXml.value('sum(//Credit)','decimal(16,4)') AS SumCredit
      ,t.YourXml.value('sum(//Debit)','decimal(16,4)') AS SumDebit
FROM @tbl t;