SQL 服务器 - 尝试格式化 table,可能使用 PIVOT
SQL Server - trying to format a table, maybe with PIVOT
所以我得到了这个 table
Email Username
------------------------- -------------------------
a@a.com a1
a@a.com a2
a@a.com a3
a@a.com a4
b@b.com b1
b@b.com b2
b@b.com b3
b@b.com b4
c@c.com c1
c@c.com c2
c@c.com c3
c@c.com c4
(12 row(s) affected)
但我希望每个电子邮件地址都出现一次,然后在它后面列出所有关联的用户名,如果可能的话..
感谢任何帮助,
干杯。
编辑
好吧,很明显,所有用户名都将放在一列中,所有用户名都连接在一起,听起来有点傻,但这就是我被要求的。
我想要的输出是
Email Username
------------------------- -------------------------
a@a.com a1, a2, a3, a4
b@b.com b1, b2, b3, b4
c@c.com c1, c2, c3, c4
d@d.com d1, d2, d3, d4
declare @t table (Id Varchar(10),username varchar(10))
insert into @t(Id,username)values ('a@a.com','a1'), ('a@a.com','a2'), ('a@a.com','a3'),
select DISTINCT Id,substring(
(
Select ','+t.username AS [text()]
From @t t
Where t.Id = t.Id
ORDER BY tt.Id
For XML PATH ('')
), 2, 1000)Username from @t tt
尝试使用 FOR XML PATH
select
Email,
Username =
stuff((
select
', ' + t2.Username
from #table1 t2
where
t2.Email = t1.Email
group by t2.Username
for xml path(''), type).value('.', 'varchar(max)'
), 1, 2, '')
from #table1 t1
所以我得到了这个 table
Email Username
------------------------- -------------------------
a@a.com a1
a@a.com a2
a@a.com a3
a@a.com a4
b@b.com b1
b@b.com b2
b@b.com b3
b@b.com b4
c@c.com c1
c@c.com c2
c@c.com c3
c@c.com c4
(12 row(s) affected)
但我希望每个电子邮件地址都出现一次,然后在它后面列出所有关联的用户名,如果可能的话..
感谢任何帮助, 干杯。
编辑
好吧,很明显,所有用户名都将放在一列中,所有用户名都连接在一起,听起来有点傻,但这就是我被要求的。
我想要的输出是
Email Username
------------------------- -------------------------
a@a.com a1, a2, a3, a4
b@b.com b1, b2, b3, b4
c@c.com c1, c2, c3, c4
d@d.com d1, d2, d3, d4
declare @t table (Id Varchar(10),username varchar(10))
insert into @t(Id,username)values ('a@a.com','a1'), ('a@a.com','a2'), ('a@a.com','a3'),
select DISTINCT Id,substring(
(
Select ','+t.username AS [text()]
From @t t
Where t.Id = t.Id
ORDER BY tt.Id
For XML PATH ('')
), 2, 1000)Username from @t tt
尝试使用 FOR XML PATH
select
Email,
Username =
stuff((
select
', ' + t2.Username
from #table1 t2
where
t2.Email = t1.Email
group by t2.Username
for xml path(''), type).value('.', 'varchar(max)'
), 1, 2, '')
from #table1 t1