0

我需要一些有关 sql 查询的帮助。

我有两张桌子USERSENDPOINT。对于每个用户,表中定义了 3 行,ENDPOINT例如

USER   ENDPOINT      ENDPOINTTYPE
123    123456        HomePhone
123    456789        CellPhone
123    A@gmail.com   Email

我想在一行中显示这些数据,例如

USER   HomePhone   CellPhone   Email

你能告诉我实现这一目标的方法吗?

非常感谢!

4

2 回答 2

4

这种类型的数据转换称为数据透视。SQL Server 具有从 SQL Server 2005 开始的数据透视函数。

在 SQL Server 2005 之前,这可以使用带有CASE表达式的聚合函数来完成:

select [user],
  max(case when ENDPOINTTYPE = 'HomePhone' then EndPoint end) HomePhone,
  max(case when ENDPOINTTYPE = 'CellPhone' then EndPoint end) CellPhone,
  max(case when ENDPOINTTYPE = 'Email' then EndPoint end) Email
from yourtable
group by [user];

请参阅SQL Fiddle with Demo

如果您使用的是 SQL Server 2005+,则数据透视查询将如下所示:

select *
from
(
  select [user], endpoint, endpointtype
  from yourtable
) src
pivot
(
  max(endpoint)
  for endpointtype in (HomePhone, CellPhone, Email)
) piv

请参阅带有演示的 SQL Fiddle

如果您提前知道这些值,则上述查询非常有用。如果你不这样做,那么你会想要使用动态 sql:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(ENDPOINTTYPE) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [USER],' + @cols + ' from 
             (
                select [USER], [ENDPOINT], [ENDPOINTTYPE]
                from yourtable
            ) x
            pivot 
            (
                max(ENDPOINT)
                for ENDPOINTTYPE in (' + @cols + ')
            ) p '

execute(@query)

请参阅带有演示的 SQL Fiddle

所有查询都返回相同的结果:

| USER | HOMEPHONE | CELLPHONE |       EMAIL |
----------------------------------------------
|  123 |    123456 |    456789 | A@gmail.com |
于 2013-01-11T19:42:19.010 回答
2

尝试这样的事情:

SELECT 
    U.[User], 
    EP1.EndPoint as 'HomeEndpoint', EP1.Endpotintype as 'HomeEndpointType', 
    EP2.EndPoint as 'CellEndpoint', EP2.Endpotintype as 'CellEndpointType', 
    EP3.EndPoint as 'EmailEndpoint', EP3.Endpotintype as 'EmailEndpointType'
FROM Users U
    LEFT JOIN EndPoint EP1 ON U.[User] = EP1.[User] AND EP1.EndPointType = 'HomePhone'
    LEFT JOIN EndPoint EP2 ON U.[User] = EP2.[User] AND EP2.EndPointType = 'CellPhone'
    LEFT JOIN EndPoint EP3 ON U.[User] = EP3.[User] AND EP3.EndPointType = 'Email'

或者只返回这 4 列:

SELECT 
    U.[User], 
    EP1.EndPoint as 'Home Phone', 
    EP2.EndPoint as 'Cell Phone', 
    EP3.EndPoint as 'Email'
FROM Users U
    LEFT JOIN EndPoint EP1 ON U.[User] = EP1.[User] AND EP1.EndPointType = 'HomePhone'
    LEFT JOIN EndPoint EP2 ON U.[User] = EP2.[User] AND EP2.EndPointType = 'CellPhone'
    LEFT JOIN EndPoint EP3 ON U.[User] = EP3.[User] AND EP3.EndPointType = 'Email'

这是SQL Fiddle - 注意,我将列 User 更改为 UserId 因为它是保留字(或者您可以使用括号)。

于 2013-01-11T19:27:07.590 回答