我有一个用户表,每个用户都有自己的电子邮件地址/用户名/密码等。
我有一个附加电子邮件的辅助表格,用户可以将其添加到他们的帐户中。两者之间的唯一链接是用户ID。
我正在尝试更新一些报告功能以准确显示这些其他电子邮件,但我希望它们全部都在一行中,并具有连续的列名。我在这方面的灵活性有限,需要将逻辑完全包装在select语句中。
目前,我正在使用Join引入第二个emailS表,并抓住emailAddress列。但是,这导致同一用户的多行,只有电子邮件地址不同,我希望它们可以压缩为一行,多列。
当前表的设置如下:
UsersXEmails
USERID | EMAILADDRESSID | EMAILADDRESS
-------------------------------------------
001 100 email1@test.com
001 200 email2@test.com
001 300 email3@test.com
002 400 testing1@gmail.com
002 500 testing2@gmail.com
003 600 foobar@gmail.com
是否可以在报告中包含以下输出:
USERNAME | EMAIL | ADDITIONALEMAIL1 | ADDITIONALEMAIL2 | ADDITIONALEMAIL3
------------------------------------------------------------------------------
Bob | bob@bob.com |email1@test.com |email2@test.com | email3@test.com
Fred | fred@fred |testing1@gmail.com |testing2@gmail.com| |
George| george@g.com|foobar@gmail.com | |
答案 0 :(得分:0)
对我来说,它可以处理item列,因为我可以控制动态生成的数据透视表的大小。您可以尝试下一个代码
CREATE TABLE #Table
(
UserId INT,
item INT,
EmailAddressID INT,
EmailAddress VARCHAR(50)
);
INSERT INTO #Table
SELECT '1', '1','1', 'email2@test.com' UNION ALL
SELECT '1', '2','2', 'email1@test.com' UNION ALL
SELECT '1', '3','3', 'email4@test.com' UNION ALL
SELECT '1', '4','4', 'email5@test.com'UNION ALL
SELECT '2', '1','5', 'email1@test.com' UNION ALL
SELECT '2', '2','6', 'email2@test.com' UNION ALL
SELECT '2', '3','7', 'email3@test.com' UNION ALL
SELECT '2', '4','8', 'email4@test.com' UNION ALL
SELECT '2', '5','9', 'email5@test.com' UNION ALL
SELECT '3', '1','10', 'email1@test.com' UNION ALL
SELECT '3', '2','11', 'email2@test.com'
DECLARE @MaxItem INT
SELECT TOP 1 @MaxItem = UserId
FROM
(SELECT UserId, COUNT(1) AS cont
FROM #Table
GROUP BY UserId) a
GROUP BY
UserId
ORDER BY
MAX(a.cont) DESC
DECLARE @columns VARCHAR(MAX);
DECLARE @sql NVARCHAR(max)
SET @columns = STUFF((SELECT ',' + QUOTENAME(item)
FROM
(SELECT item
FROM #Table
WHERE UserId = @MaxItem) AS T
ORDER BY item
FOR XML PATH('')), 1, 1, '');
--SELECT * FROM ( SELECT UserId, EmailAddress,EmailAddressID FROM #Table ) AS T PIVOT ( MAX(EmailAddress) FOR EmailAddressID IN ([1],[2],[3],[4],[5]) ) AS P order by UserId;
SET @sql = N'SELECT *
FROM
(SELECT UserId, EmailAddress, item
FROM #Table) AS T
PIVOT
(MAX(EmailAddress)
FOR item IN (' + @columns + N')) AS P
ORDER BY UserId;';
-- select @sql
EXEC sp_executesql @sql;
DROP TABLE #Table;