SQL 查询 XML nesting/grouping

SQL Query for XML nesting/grouping

我需要制作一个 XML 片段,如下所示:

<buldings>
  <building>
    <id>126433</id>
    <flats>
      <flat>
        <flat_id>ПК-01-15-01-072</flat_id>
      </flat>
      <flat>
        <flat_id>ПК-01-17-01-082</flat_id>
      </flat>
    </flats>
  </building>
</buldings>

我正在写这个sql:

select la.tisa_idcorpusdomclick [id]
    ,(
        select a.tisa_code [flat/flat_id] 
         from tisa_Article a 
         where 
               a.tisa_LayoutId = la.tisa_LayoutId 
           and a.tisa_ArticleId = la.tisa_ArticleId
         for xml path('flats'), type
      )
from (
       select l.tisa_idcorpusdomclick
             ,l.tisa_LayoutId
             ,a.tisa_ArticleId
         from tisa_layout l left join 
              tisa_article a on a.tisa_LayoutId = l.tisa_LayoutId 
        where l.tisa_idcorpusdomclick is not null 
          and a.statuscode = 4 
          and a.tisa_ArticleTypeCode = 2) la
for xml path('building'), root('buldings')

那是 returns 我错了 xml。我需要将所有单位放入节点构建 - >单位。有任何想法吗?

您还需要为嵌套的 XML 查询指定 root。像这样:

-- test data
with 
buildings(building_id) as (select '126433')
,flats(flat_id, building_id) as (
    select N'ПК-01-15-01-072', '126433'
    union
    select N'ПК-01-17-01-082', '126433'
)

-- actual query
select 
    building_id [id]
    ,(  select flat_id
        from flats
        where building_id = buildings.building_id
        for xml path('flat'), root('flats'), type
    )
from buildings
for xml path('building'), root('buildings')

在 SSMS 中试试这个,看看它是否能让你朝着正确的方向前进。

DECLARE @building TABLE ( id VARCHAR(10) );
INSERT INTO @building ( id ) VALUES ( '126433' );

DECLARE @flats TABLE ( id VARCHAR(10), flat_id VARCHAR(50) );
INSERT INTO @flats ( id, flat_id ) VALUES ( '126433', 'NK-01-15-01-072' ), ( '126433', 'NK-01-17-01-082' );

SELECT
    bldg.id, flats.flats AS 'flats'
FROM @building bldg
CROSS APPLY (
    SELECT CAST( (
        SELECT flat.flat_id FROM @flats flat WHERE flat.id = bldg.id ORDER BY flat.flat_id FOR XML PATH( 'flat' )
    ) AS XML ) AS flats
) AS flats
ORDER BY bldg.id
FOR XML PATH( 'building' ), ROOT( 'buildings' );

Returns

<buildings>
  <building>
    <id>126433</id>
    <flats>
      <flat>
        <flat_id>NK-01-15-01-072</flat_id>
      </flat>
      <flat>
        <flat_id>NK-01-17-01-082</flat_id>
      </flat>
    </flats>
  </building>
</buildings>