0

我想在一个语句中创建多个 XML 文件/结果行。

我有的:

with invoices as (
    select '1' HID, 'Test1' HData, '1' PID, 'Pos1' PData union
    select '1' HID, 'Test1' HData, '2' PID, 'Pos2' PData union
    select '1' HID, 'Test1' HData, '3' PID, 'Pos3' PData union
    select '2' HID, 'Test2' HData, '4' PID, 'Pos1' PData union
    select '2' HID, 'Test2' HData, '5' PID, 'Pos2' PData union
    select '2' HID, 'Test2' HData, '6' PID, 'Pos3' PData
)
select
    case when GROUPING_ID(PID) = 0 then 4
        when GROUPING_ID(HData) = 0 then 3
        when GROUPING_ID(HID) = 0 then 2
        else 1 end tag,
    case when GROUPING_ID(PID) = 0 then 2
        when GROUPING_ID(HData) = 0 then 2
        when GROUPING_ID(HID) = 0 then 1
        else null end parent,
    null [Root!1],
    HID [Invoice!2!HID],
    HData [Header!3!HData!Element],
    PID [Pos!4!PID],
    PData [Pos!4!PData!Element]
from invoices
group by grouping sets ((), (HID), (HID, HData), (HID, HData, PID, PData))
order by HID, HData, PID
for xml explicit, type;

我得到什么: 得到

我想要的是: 想

这可能吗?如何做到这一点?

4

1 回答 1

1

您只需要XML为每个 distinct 生成输出HID

;WITH invoices as (
    select '1' HID, 'Test1' HData, '1' PID, 'Pos1' PData union
    select '1' HID, 'Test1' HData, '2' PID, 'Pos2' PData union
    select '1' HID, 'Test1' HData, '3' PID, 'Pos3' PData union
    select '2' HID, 'Test2' HData, '4' PID, 'Pos1' PData union
    select '2' HID, 'Test2' HData, '5' PID, 'Pos2' PData union
    select '2' HID, 'Test2' HData, '6' PID, 'Pos3' PData
)
SELECT 
   XMLColumn = (
      select
         case when GROUPING_ID(PID) = 0 then 4
              when GROUPING_ID(HData) = 0 then 3
              when GROUPING_ID(HID) = 0 then 2
              else 1 
         end tag,
         case when GROUPING_ID(PID) = 0 then 2
              when GROUPING_ID(HData) = 0 then 2
              when GROUPING_ID(HID) = 0 then 1
              else null 
         end parent,
         null [Root!1],
         HID [Invoice!2!HID],
         HData [Header!3!HData!Element],
         PID [Pos!4!PID],
         PData [Pos!4!PData!Element]
      from invoices
      WHERE i.HID = HID
      group by grouping sets ((), (HID), (HID, HData), (HID, HData, PID, PData))
      order by HID, HData, PID
      for xml explicit, type
   )
FROM invoices i
GROUP BY HID
于 2022-02-17T09:53:30.623 回答