TSQL透视字符串

时间:2015-04-27 09:26:45

标签: sql sql-server string tsql pivot

我很抱歉,因为我知道这是一个在各种情况下已被多次回答的问题。然而,经过一个小时的尝试并且未能适应我已经找到的需要的例子,我得出的结论是我是一个白痴,需要特定于我的数据的帮助......

我有一个返回数据的视图如下:

SELECT * 
FROM vwPersonMainContactDetails

输出:

PersonID  | ContactMethod   | ContactValue
----------+-----------------+-----------------
1           Email             Bob@abc.com
1           Mobile            07777 777777
2           Email             kate@abc.com
2           Mobile            07766 666666
3           Email             jo@abc.com
3           Mobile            07755 555555

我需要的是返回如下结构的数据:

PersonID  |  Mobile        |  Email
----------+----------------+--------------------------
1            07777 777777     bob@abc.com
2            07766 666666     kate@abc.com
3            07755 555555     jo@abc.com

有人可以帮忙吗?我知道PIVOT将是答案,但我真的很难让它适合我...

非常感谢

安德鲁

3 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server 2005+,则可以执行以下操作:

SELECT
    *
FROM
(
SELECT
    PersonID,
    ContactMethod,
    ContactValue
FROM
    vwPersonMainContactDetails
) AS SourceTable
PIVOT
(
    MAX(ContactValue)
    FOR ContactMethod IN ([Email],[Mobile])
) AS pvt

如果你没有使用mssql,你可以这样做:

SELECT
    PersonID,
    MAX(CASE WHEN ContactMethod='Mobile' THEN ContactValue ELSE NULL END) AS Mobile,
    MAX(CASE WHEN ContactMethod='Email' THEN ContactValue ELSE NULL END) AS Email
FROM
    vwPersonMainContactDetails
GROUP BY
    PersonID

<强>参考:

答案 1 :(得分:1)

如果我们看一下Pivot的语法:

SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    ...
    [last pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>)
    AS <alias for the source query>
PIVOT
(
    <aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;
  1. 在这种情况下,聚合函数可以是:max/min
  2. 正在汇总的列:ContactValue = EmailMobile
  3. 现在在Pivot中,所有留在源表(此处为T)的列都被考虑进行分组,在这种情况下,它将是PersonID,因此Pivot变为:

    SELECT PersonID, -- <non-pivoted column>, Mobile , --[first pivoted column] AS <column name>, Email--[second pivoted column] AS <column name>, FROM ( SELECT PersonID ,ContactValue,ContactMethod from vwPersonMainContactDetails)-- query that produces the data>) AS T --<alias for the source query> PIVOT ( max(ContactValue) --<aggregation function>(<column being aggregated>) FOR [ContactMethod] --<column that contains the values that will become column headers>] IN ( [Mobile],[Email]--[first pivoted column], [second pivoted column], ) )as pvt order by PersonID asc --<optional ORDER BY clause>; DEMO

答案 2 :(得分:0)

可读性的另一种方式:

SELECT PersonID, [Email], [Mobile]
FROM [TABLE]
PIVOT (MAX(ContactValue) FOR ContactMethod IN ([Email], [Mobile])) AS PIV