2016-08-04 143 views
-1

我有一个表location,它包含id列中的值A1, A2, A3...等。我还有一个表location_color这样的:SQL查询的逗号分隔结果

A1 blue 
A1 red 
A1 green 
A2 yellow 
A2 red 
A3 blue 
A3 red 
. 
. 

现在我想查询这样的结果会是这样

blue,red,green 
yellow,red 
Blue, red 

我的查询是

select location_color.color 
from location_color 
where location.id = location_color.location_id 

,但它不工作。

+1

在MySQL中,你可以使用'GROUP BY'和'GROUP_CONCAT()' –

+3

哪个RDBMS(供应商和版本)?标记* sql *是不够的... – Shnugo

+0

你没有包含'location'表。但是,当你没有使用'location'表中的任何东西时,为什么你想拥有'where'子句?只要把那个'出去吧。 – trincot

回答

1

假设你正在使用SQL Server,这里是你可以用什么:

SELECT location_id, stuff((
     select DISTINCT ',' + u.location_color 
     from #temp u 
     where u.location_id = t.location_id 
     for xml path('') 
    ),1,1,'') as location_color_csv 
FROM #temp t 
GROUP BY t.location_id