如何将此 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
我最初的问题是我需要选择完整的主表以及每行的所有详细信息。
国家/地区:
id title
1 SLO
2 AUT
邮政编码:
id country_id code title
1 1 1000 Lj
2 1 2000 Mb
3 2 22180 Vi
4 2 22484 De
期望的结果:
1 SLO 1000;Lj|2000;MB
2 AUT 22180;Vi|22484;De
不是:
1 SLO 1000 Lj
1 SLO 2000 Mb
2 AUT 22180 Vi
2 AUT 22484 De
最好的解决方案是使用 FOR JSON ,但不幸的是我需要 2008 年或至少 2012 年的支持。
使用左连接,所有主数据都会重复以进行详细计数,但我不想这样做。更糟糕的是,选择所有国家/地区,然后在 for 循环中为每个国家/地区调用 post_codes
上的 select。
最佳答案
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
-- 如果 t.code 是 Number,则将其转换为 VARCHAR
关于sql-server - SQL Server array_agg(主 - 详细),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41137863/