Comma Separated values with SQL Query

后端 未结 4 885
孤街浪徒
孤街浪徒 2020-11-30 06:00

My SQL table is like following

City_Code     Post_Code    Post_Code_Description
100           A1           ABC
100           C8           XYZ
100           Z         


        
4条回答
  •  无人及你
    2020-11-30 06:38

    If you are using MySQL you can use GROUP_CONCAT()

    select City_Code, 
         GROUP_CONCAT(Post_Code) Post_Code, 
         GROUP_CONCAT(Post_Code_Description) post_code_description
    from yourtable
    group by City_Code
    

    For SQL Server you can use STUFF() and FOR XML PATH()

    select city_code,
        Stuff((SELECT ', ' + post_code 
                FROM yourtable t2
                where t1.city_code = t2.city_code
                FOR XML path('')),1,1,'') Post_Code,
        Stuff((SELECT ', ' + post_code_description
                FROM yourtable t2
                where t1.city_code = t2.city_code
                FOR XML path('')),1,1,'') post_code_description
    from yourtable t1
    group by city_code
    

提交回复
热议问题