我正在使用SQL Server2008。我具有下表中的数据:
Team Email Groups
------- ------------------ ------
|Team1|-|email0@email.com|-|A|
|Team1|-|email1@email.com|-|B|
|Team1|-|email2@email.com|-|C|
|Team2|-|email3@email.com|-|A|
|Team2|-|email4@email.com|-|B|
|Team2|-|email5@email.com|-|C|
我想以这种格式获取数据:
Team A B C
------- ------------------ ------------------ ------------------
|Team1|-|email0@email.com|-|email1@email.com|-|email2@email.com|
|Team2|-|email3@email.com|-|email4@email.com|-|email5@email.com|
我怎样才能做到这一点?
使用PIVOT您可以执行以下操作
With SampleData AS
(
SELECT 'Team1' as Team , 'email0@email.com' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , 'email1@email.com' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , 'email2@email.com' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , 'email3@email.com' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , 'email4@email.com' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , 'email5@email.com' as email, 'C' as Groups
)
SELECT Team, A, B,C FROM
(SELECT * FROM SampleData) source
PIVOT
(MAX(email) FOR Groups IN ([A], [B], [C]) )as pvt
产生
Team A B C
----- ---------------- ---------------- ----------------
Team1 email0@email.com email1@email.com email2@email.com
Team2 email3@email.com email4@email.com email5@email.com
查看有效的Data.SE示例
在不支持PIVOT的数据库中,您可以改为对表进行多次联接。尽管您可能还是想这样做,但是正如GBN所指出的那样,因为我们没有使用聚合。
With SampleData AS
(
SELECT 'Team1' as Team , 'email0@email.com' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , 'email1@email.com' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , 'email2@email.com' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , 'email3@email.com' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , 'email4@email.com' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , 'email5@email.com' as email, 'C' as Groups
)
SELECT
source.Team,
A.email,
B.email,
C.email
FROM
(SELECT DISTINCT TEAM From SampleData) source
LEFT JOIN SampleData A
ON source.Team = A.Team
AND A.GROUPS = 'A'
LEFT JOIN SampleData B
ON source.Team = B.Team
AND B.GROUPS = 'B'
LEFT JOIN SampleData C
ON source.Team = C.Team
AND C.GROUPS = 'C'
查看有效的Data.SE示例
本文向大家介绍mysql如何将多行数据合并成一行,包括了mysql如何将多行数据合并成一行的使用技巧和注意事项,需要的朋友参考一下
问题内容: 我正在尝试不同的JOIN查询,但没有得到想要的结果。 我有2张桌子: 我找不到想要的结果。 我想得到以下结果: 问题答案: 您不能具有这样的动态列数,但是可以 将数据连接 成字符串: 或者您可以使用或手动 旋转行( 我更喜欢后一种方法,对我来说似乎更灵活,但是在某些情况下可以大大减少代码量): 您还可以将前面的语句转换为 动态SQL, 如下所示:
问题内容: 假设我在MySQL数据库中有两个表。 表格1: 表2: 从数据库中选择行时,是否有任何方法可以将第二个表中的行作为列连接到第一个表中? 直接从MySQL查询获得的期望结果是: 谢谢你的帮助! 问题答案: 这种数据转换类型称为PIVOT。MySQL没有枢轴函数,但是您可以使用带有表达式的聚合函数来复制它: 请参阅带有演示的SQL Fiddle。 这也可以使用您的多个联接来编写,并且您将在
我有一个数据帧: 现在我想把它转换成一个新的数据帧,比如 我怎样才能用熊猫做到这一点?
问题内容: 我需要将多行合并为单行,这将是简单的带有空间的连接 我希望数据帧像这样转换:(空格分隔)tempx值 我试过的 这行得通,但是它将所有列中的行合并在一起,如下所示: 有什么优雅的解决方案吗? 问题答案: 您可以使用和功能:
问题内容: 我们有些SQL杂语。说我有一个看起来像这样的结果… 61E77D90-D53D-4E2E-A09E-9D6F012EB59C | A 61E77D90-D53D-4E2E-A09E-9D6F012EB59C | B 61E77D90-D53D-4E2E-A09E-9D6F012EB59C | C 61E77D90-D53D-4E2E-A09E-9D6F012EB59C | D 7ce9