SELECT..FOR XML 内的 CASE - 避免多个元素

CASE inside SELECT..FOR XML - avoiding multiple elements

如何避免创建多个 <Debtor><Creditor> 元素。 以下是我需要改进的查询。基本上我需要在 <Creditor><Debtor> 中得到 <name><address> 取决于 CASE 条件表达的 Amt

SELECT
(SELECT  [Amt/@Curr] = t.Curr
        ,t.Amt 
        ,[EntryDetails/TxnDetails/PostClassDt] = CASE WHEN Amt < 0 THEN 'debit' END
        ,[EntryDetails/TxnDetails/PostClassCr] = CASE WHEN Amt >= 0 THEN 'return' END
        ,[EntryDetails/TxnDetails/Parties/Creditor/Name] = CASE WHEN Amt < 0 THEN Contractor END
        ,[EntryDetails/TxnDetails/Parties/Debtor/Name] = CASE WHEN Amt >= 0 THEN Contractor END
        ,[EntryDetails/TxnDetails/Parties/Creditor/Address] = CASE WHEN Amt < 0 THEN [Address] END
        ,[EntryDetails/TxnDetails/Parties/Debtor/Address] = CASE WHEN Amt >= 0 THEN [Address] END
FROM    (VALUES 
            ('EUR', -123.45, 'John Doe','St.John'),
            ('USD', 456.78, 'Jane Doe', 'St.Jane')
        ) t (Curr, Amt, Contractor, [Address])
FOR XML PATH('Entry'), TYPE
)   [Statement]
FOR XML PATH('Schema'),  ROOT('Document')

所需格式如下所示。有人帮忙吗?

<Document>
      <Schema>
        <Statement>
          <Entry>
            <Amt Curr="EUR">-123.45</Amt>
            <EntryDetails>
              <TxnDetails>
                <PostClassDt>debit</PostClassDt>
                <Parties>
                  <Creditor>
                    <Name>John Doe</Name>
                    <Address>St.John</Address>
                  </Creditor>
                </Parties>
              </TxnDetails>
            </EntryDetails>
          </Entry>
          <Entry>
            <Amt Curr="USD">456.78</Amt>
            <EntryDetails>
              <TxnDetails>
                <PostClassCr>return</PostClassCr>
                <Parties>
                  <Debtor>
                    <Name>Jane Doe</Name>
                    <Address>St.Jane</Address>
                  </Debtor>
                </Parties>
              </TxnDetails>
            </EntryDetails>
          </Entry>
        </Statement>
      </Schema>
    </Document>

更改 select 的顺序:

    SELECT
(SELECT  [Amt/@Curr] = t.Curr
        ,t.Amt 
        ,[EntryDetails/TxnDetails/PostClassDt] = CASE WHEN Amt < 0 THEN 'debit' END
        ,[EntryDetails/TxnDetails/PostClassCr] = CASE WHEN Amt >= 0 THEN 'return' END
        ,[EntryDetails/TxnDetails/Parties/Creditor/Name] = CASE WHEN Amt < 0 THEN Contractor END
        ,[EntryDetails/TxnDetails/Parties/Creditor/Address] = CASE WHEN Amt < 0 THEN [Address] END
        ,[EntryDetails/TxnDetails/Parties/Debtor/Name] = CASE WHEN Amt >= 0 THEN Contractor END
        ,[EntryDetails/TxnDetails/Parties/Debtor/Address] = CASE WHEN Amt >= 0 THEN [Address] END
FROM    (VALUES 
            ('EUR', -123.45, 'John Doe','St.John'),
            ('USD', 456.78, 'Jane Doe', 'St.Jane')
        ) t (Curr, Amt, Contractor, [Address])
FOR XML PATH('Entry'), TYPE
)   [Statement]
FOR XML PATH('Schema'),  ROOT('Document')