需要帮助Cross Tab SQL Query

时间:2011-06-21 14:24:49

标签: mysql sql sql-server-2005 sql-server-2008

这是源示例表:

    UserID  UserNameType    UserName
    1       First Name      FN1
    1       Last Name       LN1
    2       First Name      FN2
    2       Last Name       LN2
    3       First Name      FN3
    3       Last Name       LN3
    4       First Name      FN4
    4       Last Name       LN4

我想有一个SQL查询来显示我的结果,如下面给出的格式。

   
    UserID  FirstName   LastName
    1       FN1         LN1
    2       FN2         LN2
    3       FN3         LN3
    4       FN4         LN4

需要更多帮助...

Need Help

谢谢, Yugal

5 个答案:

答案 0 :(得分:3)

一个简单的交叉表方法(我个人更喜欢)是使用具有MAX(CASE WHEN ...)模式的group by运算符来控制交叉表字段。这很容易理解IMO,并且易于扩展,具有更多领域。我不确定表现。

select
    UserID,
    max(case when usernametype='First Name' then username end) as FirstName,
    max(case when usernametype='Last Name' then username end) as LastName
from
    MyTable T
group by
    UserID

答案 1 :(得分:2)

SELECT
  [fn].UserID,
  [fn].UserName,
  [ln].UserName
FROM
  yourTable AS [fn]
INNER JOIN
  yourTable AS [ln]
    ON [fn].UserID = [ln].UserID
WHERE
      [fn].UserNameType = 'FirstName'
  AND [ln].UserNameType = 'LastName'

答案 2 :(得分:1)

您可以使用子查询

SELECT 
    UserID,
    UserName as FirstName,
    (SELECT top 1 UserName 
     FROM myTable 
     WHERE UserID = t.UserID 
     and UserNameType = 'Last Name') as LastName
FROM myTable t
WHERE t.UserNameType = 'First Name'

答案 3 :(得分:1)

为了避免子查询以及可能出现的速度惩罚,请加入自己。

SELECT DISTINCT
 T1.UserID UserID, 
 T1.UserName FirstName, 
 T2.UserName LastName
FROM 
 Users T1 JOIN Users T2 
  ON T1.UserID = T2.userID
WHERE 
 T1.UserNameType = 'FirstName'
 AND T2.UserNameType = 'LastName'
编辑:现在应该修复。

答案 4 :(得分:1)

假设您有以下表格

create table #temp1
(
    UserID  int,
    usernametype varchar(10),
    username varchar(10)
)

以下是插入

insert into #temp1(userid, usernametype, username) valueS(1, 'First Name', 'FN1')
insert into #temp1(userid, usernametype, username) valueS(1, 'Last Name', 'LN1')
insert into #temp1(userid, usernametype, username) valueS(2, 'First Name', 'FN2')
insert into #temp1(userid, usernametype, username) valueS(2, 'Last Name', 'LN2')
insert into #temp1(userid, usernametype, username) valueS(3, 'First Name', 'FN3')
insert into #temp1(userid, usernametype, username) valueS(3, 'Last Name', 'LN3')
insert into #temp1(userid, usernametype, username) valueS(4, 'First Name', 'FN4')
insert into #temp1(userid, usernametype, username) valueS(4, 'Last Name', 'LN4')

enter image description here

SQl查询

SELECT  userid, [First Name], [Last Name]
FROM    
( 
    SELECT userid, usernametype, username FROM #temp1
) 
p 
PIVOT 
( 
    Max(username) FOR usernametype 
    IN ([First Name], [Last Name])
) AS pvt

最终结果集

enter image description here