2
我想使用SQL Server中的存储过程合并我的通知数据。我写了查询,但在这个查询中,我得到的不止是多行用户数据。使用SQL Server将多行合并为一行?
我想合并关注者通知。比如“用户a关注用户b,然后用户b”就会收到类似“用户a开始关注你”的通知。再次“用户c关注用户b”,然后“用户b再次收到类似”“用户c关注你”的通知。
再次“用户d再次跟随用户b,然后用户b就像获得通知一样”。但是现在我想像这样通知合并:“用户a,b和另外1个用户开始关注你”。
这是我的存储过程:
SELECT
N.NotificationId,
N.UserId,
N.ActionUserId,
(CASE WHEN N.NotificationTypeId = 1 THEN 1
WHEN N.NotificationTypeId = 7 THEN 3
ELSE
2
END) AS TypeId,
AU.ProfileImage,
AU.UserName,
N.IsRead,
(CASE WHEN N.NotificationTypeId = 1 THEN 1
WHEN N.NotificationTypeId = 7 THEN 3
ELSE 2
END) AS TypeId,
N.NotificationTypeId,
N.InsertDateTime
FROM
Notifications N
INNER JOIN
Users U ON N.UserId = U.UserId
INNER JOIN
Users AU ON N.ActionUserId = AU.UserId
ORDER BY
N.InsertDateTime DESC
这是我的当前O/P =>
NotificationId | UserId | ActionUserId | UserName | NotificationTypeId | InsertDateTime | ProfileImage
6 20 15 hbc 1 2017-06-22 17:14:16.803 20170416032403869.jpeg
5 20 16 tyu 1 2017-06-22 17:12:12.297 20170416031522534.jpeg
4 20 17 opl 1 2017-06-22 17:11:58.060 20170416031250102.jpeg
3 10 11 abc 1 2017-06-22 16:14:16.803 20170416032403867.jpeg
2 10 12 xyz 1 2017-06-22 16:14:12.297 20170416031522533.jpeg
1 10 13 rty 1 2017-06-22 16:13:58.060 20170416031250101.jpeg
这是我的例外O/P =>
NotificationId | UserId | ActionUserId | UserName | NotificationTypeId | InsertDateTime | ProfileImage | NotificationText
6 20 15 hbc 1 2017-06-22 17:14:16.803 20170416032403869.jpeg hbc,tyu and 1 other users followed you
3 10 11 abc 1 2017-06-22 16:14:16.803 20170416032403867.jpeg abc,xyz and 1 other users followed you
创建测试数据=>
declare @Notifications table(NotificationID int, UserID int, ActionUserID int, NotificationTypeID int, InsertDateTime datetime);
declare @Users table(UserID int, UserName nvarchar(10), ProfileImage nvarchar(50))
insert into @Notifications values (6,20,15,1,'2017-06-22 17:14:16.803'),(5,20,16,1,'2017-06-22 17:12:12.297'),(4,20,17,1,'2017-06-22 17:11:58.060'),(3,10,11,1,'2017-06-22 16:14:16.803'),(2,10,12,1,'2017-06-22 16:14:12.297'),(1,10,13,1,'2017-06-22 16:13:58.060');
insert into @Users values (15,'hbc','20170416032403869.jpeg'),(16,'tyu','20170416031522534.jpeg'),(17,'opl','20170416031250102.jpeg'),(10,'aaa',''),(11,'abc','20170416032403867.jpeg'),(12,'xyz','20170416031522533.jpeg'),(13,'rty','20170416031250101.jpeg');
@TimBiegeleisen你能帮我怎么做才能合并我的数据? – Edit
@marc_s你能帮助我请怎么做 – Edit
当你问这样一个问题时,你应该提供:1)CREATE语句所涉及的表,如果没有所有字段,那么所有相关字段; 2)INSERT语句用充足的测试数据填充这些表(不需要是真实的数据)来测试结果;以及3)给出测试数据的期望输出样本。那么你有更好的机会获得帮助。 –