我有一個表我可以從子查詢中獲得逗號分隔的值嗎?如果沒有,如何做到這一點?
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
,但沒有奏效...
的可能重複[以MS SQL Server 2005中模擬GROUP_CONCAT MySQL的函數?(http://stackoverflow.com/questions/451415/simulating- group-concat-mysql-function-in-ms-sql-server-2005) –
你正在尋找的功能是一個GROUP BY串聯。 MySQL有這個內置的,但MS-SQL沒有。有關於此的其他堆棧溢出文章,如:http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005 – Richthofen
請參閱此 http: //blog.sqlauthority.com/2009/11/25/sql-server-comma-separated-values-csv-from-table-column/ – Madhivanan