2012-07-03 29 views
3

我有一個表我可以從子查詢中獲得逗號分隔的值嗎?如果沒有,如何做到這一點?

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

印度和馬哈拉施特拉,孟加拉,卡納塔克

第二

美國和阿拉斯加California

我試過我喜歡這

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

,但沒有奏效...

+2

的可能重複[以MS SQL Server 2005中模擬GROUP_CONCAT MySQL的函數?(http://stackoverflow.com/questions/451415/simulating- group-concat-mysql-function-in-ms-sql-server-2005) –

+2

你正在尋找的功能是一個GROUP BY串聯。 MySQL有這個內置的,但MS-SQL沒有。有關於此的其他堆棧溢出文章,如:http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005 – Richthofen

+1

請參閱此 http: //blog.sqlauthority.com/2009/11/25/sql-server-comma-separated-values-csv-from-table-column/ – Madhivanan

回答

12
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

這是一個有點討厭的和潛在的緩慢,如果在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 
+0

你正在認真地將你的CTE錨定在一行上,而不是所有的起始行上所有國家一次? OUCHIE! – ErikE

相關問題