【问题标题】:Finding duplicates and returning them with related information in XML查找重复项并将其与 XML 中的相关信息一起返回
【发布时间】:2015-07-22 11:47:00
【问题描述】:

以下查询返回具有给定订单号的所有订单。如何重写它,以便返回指定的重复订单 ID 及其各自的 custid 和/或公司名称?

DECLARE @x AS XML;
SET @x = N'
<CustomersOrders>
  <Customer custid="1">
     <companyname>Customer NABCD</companyname>
       <Order orderid="10692">
         <orderdate>2013-11-03</orderdate>
       </Order>
        <Order orderid="10702">
          <orderdate>2007-10-13</orderdate>
        </Order>
        <Order orderid="10693">
          <orderdate>2008-03-16</orderdate>
        </Order>
      </Customer>
      <Customer custid="2">
        <companyname>Customer HMKLI</companyname>
        <Order orderid="10308">
          <orderdate>2006-09-18</orderdate>
        </Order>
        <Order orderid="10693">
          <orderdate>2008-03-04</orderdate>
        </Order>
  </Customer>
</CustomersOrders>';

SELECT @x.query('//Order[@orderid=10693]')

编辑:

输出格式可以是...

<CustomersOrders>
    <Customer custid="1">
         <companyname>Customer NABCD</companyname>
            <Order orderid="10693"/>
    </Customer>
    <Customer custid="2">
          <companyname>Customer HMKLI</companyname>
             <Order orderid="10693"/>
    </Customer>
</CustomersOrders>

或者(甚至更好)

  <CustomersOrders>
    <Order orderid="10693">
        <Customer custid="1">
             <companyname>Customer NABCD</companyname>
        </Customer>
        <Customer custid="2">
              <companyname>Customer HMKLI</companyname>
        </Customer>
    </Order>
  </CustomersOrders>'

【问题讨论】:

  • 鉴于该示例 XML,确切的输出应该是什么,您可以发布预期的输出吗?
  • 嗨,请看我的编辑。
  • 两个预期输出的格式都不是很好(某些元素没有正确关闭)
  • 道歉 - 现已更正。

标签: sql-server xml xquery-sql


【解决方案1】:

这是一种可能的方式:

SELECT @x.query('
    <CustomersOrders>
    {
        for $order in //Order[@orderid=10693]
        let $customer := $order/..
        return 
            <Customer custid="{$customer/@custid}">
                {$customer/companyname}
                <Order orderid="{$order/@orderid}"/>
            </Customer>
    }
    </CustomersOrders>
')

输出:

<CustomersOrders>
  <Customer custid="1">
    <companyname>Customer NABCD</companyname>
    <Order orderid="10693" />
  </Customer>
  <Customer custid="2">
    <companyname>Customer HMKLI</companyname>
    <Order orderid="10693" />
  </Customer>
</CustomersOrders>

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    相关资源
    最近更新 更多