我有这种查询类型,
select StateName ,countryName
from country_master left join state_master on country_master.countryID = state_master.countryID
产生以下结果,
古吉拉特邦印度
德里印度
印度人力资源印度委员会 NY USA
LA USA
芝加哥美国
WDC USA
伦敦英国
我想将此结果放在单行中,其关系如
印度 - 古吉拉特邦德里HR MP
美国 - 纽约洛杉矶芝加哥 - 伦敦
有任何构建此查询的想法
建议我,
谢谢,
答案 0 :(得分:2)
此问题基本上与Concatenate many rows into a single text string?重复。
以下是一种适用于Sql Server 2008的方法:
WITH Ranked ( countryID, rnk, stateName )
AS ( SELECT countryID,
ROW_NUMBER() OVER( PARTITION BY countryID ORDER BY countryID ),
CAST( stateName AS VARCHAR(8000) )
FROM state_master),
AnchorRanked ( countryID, rnk, stateName )
AS ( SELECT countryID, rnk, stateName
FROM Ranked
WHERE rnk = 1 ),
RecurRanked ( countryID, rnk, stateName )
AS ( SELECT countryID, rnk, stateName
FROM AnchorRanked
UNION ALL
SELECT Ranked.countryID, Ranked.rnk,
RecurRanked.stateName + ', ' + Ranked.stateName
FROM Ranked
INNER JOIN RecurRanked
ON Ranked.countryID = RecurRanked.countryID
AND Ranked.rnk = RecurRanked.rnk + 1 )
SELECT countryName, MAX( stateName )
FROM RecurRanked
INNER JOIN country_master on RecurRanked.countryID = country_master.countryID
GROUP BY countryName;
您可以在此处看到几种提取此类技术的方法:https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
如果你的连续城市列表长度超过8000个字符,你需要小心,尽管如果这是一个问题,你可能能够做出类似varchar(max)之类的事情(除了事实之外)它可能不是查看数据的好方法。
答案 1 :(得分:0)
使用递归合并函数可以非常轻松地完成此任务。
您创建一个连接递归查询结果的函数,然后在查询中调用该函数。
我对这个问题的回答中的完整代码和示例: How to "Implode" (de-normalize/concat) multiple columns into a single column?
答案 2 :(得分:0)
Select t.countryName , isnull(Stuff((SELECT ', ' + StateName
FROM state_master where countryID = t.countryID
ORDER BY StateName
For XML PATH ('')),1,1,''),'') as c
from country_master t
答案 3 :(得分:0)
select c.countryName,
stuff((select ' '+s.StateName
from state_master as s
where s.countryID = c.countryID
for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '')
from country_master as c