If count(values) > 1, combine all values into a single cell [duplicate]

喜夏-厌秋 提交于 2019-12-10 17:28:11

问题


Possible Duplicate:
SQL Server: Can I Comma Delimit Multiple Rows Into One Column?

I would like to combine all records in a certain field into a single cell (per value from another column) if the count of the records is more than 1. For example, if I have the following code

SELECT city, count(zoo name) AS 'count of zoo name' FROM mytable

It would generate the below results

The original table looks like this

Since both Atlanta and New York have more than one zoo and Tokyo only has one zoo, the final result should look like

How would I go about doing this? I thought about using the PIVOT construct, but that creates new columns for each possible value. I would also have to write the name of every possible zoo name into the PIVOT. This would be bad form since the actual data has much more possible values of "zoo name" than the above.


回答1:


You can use XML Path to concat the column value

;With Cte(city,concat) as
(
    select city, (select a.Zoo+','
    from Sample a
    where a.city=b.city
    for XML PATH ('') )  concat
    from Sample b
    group by city
 )
Select city,left(concat, len(concat) -1) from cte

Check the result in SQL Fiddle



来源:https://stackoverflow.com/questions/11890590/if-countvalues-1-combine-all-values-into-a-single-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!