将结果集中的列结果转换为行

时间:2011-08-11 13:48:04

标签: sql pivot transpose

我有这样的结果集

Continent   Country
------- -------
Asia    Japan
Asia    Russia
Asia    India
Europe  Britain
Europe  France

来自查询

select continent,country from tablexxx

我想要格式

的结果
Continent   Country
------- -------
Asia    Japan,Russia,India
Europe  Britain,France

我听说过数据透视表。但对我来说似乎很难...... 任何有关查询的帮助请:)

这是我在SQL Server中的最终解决方案,它有效...... :)

SELECT     continents, Countries = replace
                          ((SELECT Countries AS [data()]
                              FROM tblXXX
                              WHERE  continents = a.continents
                              ORDER BY continents FOR xml path('')), ' ',  ',' )
FROM       tblXXXa
WHERE     continents IS NOT NULL
GROUP BY continents

2 个答案:

答案 0 :(得分:1)

如果您使用MySQL,则需要使用GROUP_CONCAT

示例:

SELECT continent, GROUP_CONCAT(county ORDER BY country) as Countries 
FROM tablexxx
GROUP BY continent
ORDER BY continent

链接
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

答案 1 :(得分:0)

您可以使用COALESCE函数从行构建逗号分隔的列表,如下例所示:

DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList