我在MSSQL Server 2012中有两个表,并希望将它们组合成一个新表。它们由列messageID链接。第一个表(消息)有
messageID
sender
date
第二个表( recipientInfo )有
messageID
recipient
主要问题是在消息中,messageID是主键,因此是唯一的。在 recipientInfo 中,messageID不是唯一的(因为一条消息可以有多个收件人)。我想要一个带有
的新表答案 0 :(得分:4)
也许是这样的(如果你使用的是MSSQL 2005 +):
CREATE TABLE NewTable
(
messageID INT,
sender VARCHAR(100),
recipient VARCHAR(MAX),
date DATETIME
)
INSERT INTO NewTable(messageID,sender,recipient,date)
SELECT
[Message].messageID,
[Message].sender,
STUFF
(
(
SELECT
',' +recipient
FROM
recipientInfo
WHERE
recipientInfo.messageID=[Message].messageID
FOR XML PATH('')
)
,1,1,'') AS recipient,
[Message].date
FROM
[Message]
答案 1 :(得分:1)
您想创建一个视图并将现有表保留在那里吗?或者你想永久地合并这两个表?
SELECT m.messageID, m.sender, m.date, r.recipient
INTO New_Table
FROM Message m LEFT OUTER JOIN
recipientinfo r on m.messageID = r.messageID
答案 2 :(得分:0)
select msg.messageID, msg.sender, rep.recipient, msg.date
from Message msg
left outer join recipientInfo rep on msg.messageID = rep.messageID
答案 3 :(得分:0)
您可能需要在此处对拼写进行排序
select sender,date,( select recipient+chr(10) from receipientInfo as r where r.messageid = m.messageid order by r.recipient FOR XML PATH ('')) as receipents from message as m
答案 4 :(得分:-1)
你可以合并两个表
https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
这可能更合适,并且有更多方法可以做到这一点