如何避免创建多个<Debtor>
和<Creditor>
元素。
以下是我需要改进的查询。基本上,我需要在<name>
或<address>
内同时获取<Creditor>
和<Debtor>
,具体取决于Amt
条件所表达的CASE
。
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>
答案 0 :(得分:1)
更改您选择的顺序:
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')