4

我有一张桌子

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 列)将是

印度和马哈拉施特拉邦、孟加拉邦、卡纳塔克邦

第二

美国和阿拉斯加,加利福尼亚

我试过我喜欢这个

select distinct
    OutTable.Country,
    (select State
     from Country_State_Mapping InnerTable
     where InnerTable.Country = OutTable.Country)
from Country_State_Mapping AS OutTable

但没有工作...

4

2 回答 2

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
于 2012-07-03T13:01:21.057 回答
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
于 2012-07-03T13:21:31.967 回答