我有一个连接多个表的MS SQL查询,结果示例如下:
EmailAddress Column2
--------------------- ----------------
sean@abc.com Value1
sean@abc.com Value2
test@abc.com Value5
What I really want to achieve are the following results:
EmailAddress Column2
--------------------- ------------------
sean@abc.com Value1, Value2
test@abc.com Value5
对于具有相同电子邮件地址的每一行,还有其他列相同。任何人都可以帮我使用SQL来返回不同的电子邮件地址并连接column2信息吗?
感谢您的任何反馈。
答案 0 :(得分:1)
答案 1 :(得分:0)
在SQL Server 2005+
:
WITH q AS
(
SELECT 'sean@abc.com' AS address, 'Value1' AS value
UNION ALL
SELECT 'sean@abc.com', 'Value2'
UNION ALL
SELECT 'test@abc.com', 'Value5'
)
SELECT (
SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY value) > 1 THEN ', ' ELSE '' END + value
FROM q qi
WHERE qi.address = qo.address
FOR XML PATH('')
)
FROM (
SELECT DISTINCT address
FROM q
) qo
答案 2 :(得分:0)
杰里米的答案相同,但我会用 XML PATH 技巧使用other答案