将自定义名称作为columnNames的数据透视表

时间:2016-02-23 11:04:42

标签: sql sql-server pivot

如何使用单列旋转表格。

我的选择查询的结果集包含单列和3行。 即我的选择查询如下: -

contactList table have following columns.
ContactID, PhNumbers, PhTYpe, ContactPersonID

select PhNumbers,PhType from contactList where ContactPersonID=3

PhNumbers     PhType
1234567890      1
3456789013      2
4545466756      3

这3行对应3种电话号码

我需要像这样的输出

homePhone     MobilePhone     WorkPhone
1234567890    3456789013      4545466756

3 个答案:

答案 0 :(得分:1)

  DECLARE
    @SQL varchar(MAX),
    @ColumnList varchar(MAX)

SELECT @ColumnList=
       COALESCE(@ColumnList + ',','') + QUOTENAME(PhNumbers)
FROM
(
       SELECT DISTINCT PhNumbers
       FROM contactList 
) T


SET @SQL = '
WITH PivotData AS
(
       SELECT PhNumbers
       FROM contactList
)
SELECT
    ' + @ColumnList + '
FROM
    PivotData
PIVOT
(
    MAX(PhNumbers)
    FOR PhNumbers
    IN (' + @ColumnList + ')
) AS PivotResult'

EXEC (@SQL)

答案 1 :(得分:0)

得到了答案。谢谢你所有的帮助。

SELECT [1] as HomePhone, [2] as MobilePhone,[3] as WorkPhone,
FROM
  (select PhNumbers,PhType from contactList where ContactPersonID=3) AS     SourceTable
PIVOT
(
MAX(PhNumbers)
FOR PhType IN ([1],[2],[3])
) AS PivotTable;

答案 2 :(得分:0)

尝试此查询

选择1,2,3 从 (SELECT PhNumbers,PhType   FROM contactList其中ContactPersonID = 3)a  PIVOT(MAX(PhNumbers)FOR PhType IN(1, 2, 3))r