【发布时间】:2016-08-16 03:12:00
【问题描述】:
我有以下表格布局:
订单详情:
ItemID (PK, int, not null)
ItemName (nvarchar(450), null)
OrderID (FK, int, not null)
Discounts (nvarchar(max), null)
Discounts 列被声明为 nvarchar(max) 但数据实际上是 XML - 不知道为什么它没有被声明为 XML。我需要查询表以显示OrderID、ItemName、按比例分配的折扣、所有其他折扣以及按比例分配的总和+所有其他折扣。这是一些记录的示例。
ItemID ItemName OrderID Discounts
8610 Item 1 4227 SEE XML 4227 BELOW
8615 Item 2 4227 <DocumentElement></DocumentElement> //no discounts for this row
8620 Item 3 9387 SEE XML 9387 BELOW
XML OrderId = 4227:
<DocumentElement>
<DiscountsTable>
<DiscountDisplayName>Bundle A</DiscountDisplayName>
<DiscountValue>6.00</DiscountValue>
</DiscountsTable>
<DiscountsTable>
<DiscountDisplayName>Bundle B</DiscountDisplayName>
<DiscountValue>25.00</DiscountValue>
</DiscountsTable>
</DocumentElement>
OrderId = 9387 的 XML:
<DocumentElement>
<DiscountsTable>
<DiscountDisplayName>Prorated Discount</DiscountDisplayName>
<DiscountValue>6.45</DiscountValue>
</DiscountsTable>
<DiscountsTable>
<DiscountDisplayName>Bundle A</DiscountDisplayName>
<DiscountValue>5.61</DiscountValue>
</DiscountsTable>
<DiscountsTable>
<DiscountDisplayName>Bundle B</DiscountDisplayName>
<DiscountValue>23.39</DiscountValue>
</DiscountsTable>
</DocumentElement>
所以,我需要的是一个查询,它将返回 ItemID、ItemName、汇总的按比例分配的折扣、汇总的捆绑折扣以及加在一起的总折扣(按比例分配 + 捆绑 = 总折扣)。对于上面的 3 条记录,查询结果应该是这样的:
Item ID Item Name Prorated Discounts Other Discounts Total Discounts
8610 Item 1 0.00 31.00 31.00
8615 Item 2 0.00 0.00 0.00
8620 Item 3 6.45 29.00 35.45
我已尝试使用 value() 方法,但我收到一条错误消息,指出它不能与 nvarchar(max) 一起使用。如何解析 XML 列以提取聚合值?
【问题讨论】:
标签: sql sql-server xml