我正在制作一张有这样数据的表格 - 抱歉格式化,因为我是新来的
ColA Type Name Email
-----------------------
1 Type1 John yyyy@m
1 Type2 Emily xxx@m
2 Type2 Richard ooo@m
3 Type1 Rebecca pppp@m
3 Type2 Pumpkin nnnn@m
我想要一个基于Type Column
的输出COL1 TYPE1Name TYPE1Email Type2Name Type2Email
-------------------------
1 John yyyy@m Emily xxx@m
2 NULL NULL Richard ooo@m
3 Rebecca pppp@m Pumpkin nnnn@m
我尝试了2个带有枢轴的CTE并加入了它们但没有得到结果 任何建议
答案 0 :(得分:1)
加入枢轴为我工作,我得到你需要的结果,
SELECT NAME.COL1
,NAME.TYPE1Name
,email.TYPE1Email
,NAME.TYPE2Name
,email.TYPE2Email
FROM (
SELECT ColA AS COL1
,Type1 AS TYPE1Name
,Type2 AS TYPE2Name
FROM (
SELECT ColA
,NAME
,Type
FROM #table_name --Your table name here
) AS a
pivot(max(NAME) FOR Type IN (
[Type1]
,[Type2]
)) pvt
) NAME
INNER JOIN (
SELECT ColA AS COL1
,Type1 AS TYPE1Email
,Type2 AS TYPE2Email
FROM (
SELECT ColA
,Email
,Type
FROM #table_name --Your table name here
) AS a
pivot(max(Email) FOR Type IN (
[Type1]
,[Type2]
)) pvt
) email ON NAME.COL1 = email.COL1
结果如下,
COL1 TYPE1Name TYPE1Email TYPE2Name TYPE2Email
1 John yyyy@m Emily xxx@m
2 NULL NULL Richard ooo@m
3 Rebecca pppp@m Pumpkin nnnn@m
答案 1 :(得分:1)
最简单和最佳的性能是将MAX与CASE表达式一起使用。如果有更多类型可用,也可以动态创建。
SELECT
Col1 = ColA,
TYPE1Name = MAX(CASE WHEN [Type] = 'Type1' THEN [Name] END),
TYPE1Email = MAX(CASE WHEN [Type] = 'Type1' THEN [Email] END),
TYPE2Name = MAX(CASE WHEN [Type] = 'Type2' THEN [Name] END),
TYPE2Email = MAX(CASE WHEN [Type] = 'Type2' THEN [Email] END)
FROM
myTable
GROUP BY
ColA