我有一张桌子
Create table Country_State_Mapping
(
Country nvarchar(max),
State nvarchar(max)
)
有5条记录。
Insert into Country_State_Mapping values('INDIA', 'Maharastra')
Insert into Country_State_Mapping values('INDIA', 'Bengal')
Insert into Country_State_Mapping values('INDIA', 'Karnatak')
Insert into Country_State_Mapping values('USA', 'Alaska')
Insert into Country_State_Mapping values('USA', 'California')
我需要编写一个SQL查询,它会给我2条记录/ 2列,如下所示。
第一栏 Contry ,第二栏 AllStates
1条记录(2列)
India and Maharastra,Bengal,Karnatak
第二
美国和加利福尼亚州阿拉斯加
我试过我喜欢这个
select distinct
OutTable.Country,
(select State
from Country_State_Mapping InnerTable
where InnerTable.Country = OutTable.Country)
from Country_State_Mapping AS OutTable
但没有用......
答案 0 :(得分:13)
SELECT Country, AllStates =
STUFF((SELECT ', ' + State
FROM Country_State_Mapping b
WHERE b.Country = a.Country
FOR XML PATH('')), 1, 2, '')
FROM Country_State_Mapping a
GROUP BY Country
答案 1 :(得分:1)
如果Country_State_Mapping表中的记录数量很大但确实完成了工作,这有点令人讨厌并且可能会很慢。它使用SQL 2005中引入的公用表表达式的递归功能。
;WITH Base
AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY Country ORDER BY Country, [State] DESC) AS CountryRowId,
ROW_NUMBER() OVER (ORDER BY Country, [State]) AS RowId,
Country,
[State]
FROM Country_State_Mapping
),
Recur
AS
(
SELECT
CountryRowId,
RowId,
Country,
[State]
FROM Base
WHERE RowId = 1
UNION ALL
SELECT
B.CountryRowId,
B.RowId,
B.Country,
CASE WHEN R.Country <> B.Country THEN B.[State] ELSE R.[State] + ',' + B.[State] END
FROM Recur R
INNER JOIN Base B
ON R.RowId + 1 = B.RowId
)
SELECT *
FROM Recur
WHERE CountryRowId = 1
OPTION (MAXRECURSION 0)--Dangerous