SQL Server array_agg(主-详细信息)

Mak*_*kla 2 t-sql sql-server

如何将该PostgreSQL代码转换为SQL Server?

select 
    countries.title, 
    (select array_to_json(array_agg(row_to_json(t))) 
     from postcodes t 
     where t.country_id = countries.id) as codes 
from countries
Run Code Online (Sandbox Code Playgroud)

我最初的问题是我需要选择完整的主表,并且每一行都包含所有详细信息。

国家

id    title
1     SLO
2     AUT
Run Code Online (Sandbox Code Playgroud)

邮编

id  country_id  code    title
1   1           1000    Lj
2   1           2000    Mb
3   2           22180   Vi
4   2           22484   De
Run Code Online (Sandbox Code Playgroud)

所需结果:

1  SLO  1000;Lj|2000;MB
2  AUT  22180;Vi|22484;De
Run Code Online (Sandbox Code Playgroud)

不:

1  SLO  1000  Lj
1  SLO  2000  Mb
2  AUT  22180 Vi
2  AUT  22484 De
Run Code Online (Sandbox Code Playgroud)

最好的解决方案是使用FOR JSON,但是不幸的是我需要2008年或至少2012年的支持。

在左连接的情况下,所有主数据都会重复以进行详细计数,但是我不想这样做。更糟糕的是,将选择所有国家/地区,然后post_codes为for循环中的每个国家/地区调用select on 。

小智 5

select countries.title, 
       STUFF((select '|' + t.code + ';' + t.title
                from postcodes t 
                where t.country_id = countries.id
                FOR XML PATH('')
              ),1,1,'') as codes 
     from countries
Run Code Online (Sandbox Code Playgroud)

-将TAST.CAST t.code转换为VARCHAR