导致重复行的Case语句

时间:2015-07-26 08:13:05

标签: sql-server-2008

我已成功在我的应用程序中构建了消息传递功能,我有一个小问题,我需要帮助,当我向另一个用户发送电子邮件时,我将此消息插入数据库,此行的ReadDate列将由于它是新的,因为它是新的,当我从UI读取此消息时,ReadDate列将填充今天的日期。

现在我的问题是这个,给出以下查询,它返回收件箱中收到ReceipientId = @UserId的收件箱内的电子邮件。:

 Select p.Id [SenderId], p.Username, count(mr.RecipientId) [TotalMessages], up.PhotoId,
        CASE
            WHEN mr.ReadDate is null then 1 -- New message
            ELSE 0 -- Message has been read
        END AS NewMessage,
 p.LastLoggedIn, p.LoggedIn
 FROM [User].[User_Profile] p
 JOIN [MailBox].[Message] m on p.Id = m.SenderId
 JOIN [MailBox].[MessageRecipient] mr on m.Id = mr.MessageId
 LEFT JOIN [User].[User_Photos] up on p.Id = up.UserId
 where up.isProfilePic = 1 and mr.RecipientId = @UserId and mr.DeletedDate is null
 GROUP BY p.id, p.Username, mr.RecipientId, up.PhotoId, p.LastLoggedIn, p.LoggedIn,
 CASE
     WHEN mr.ReadDate is null then 1 -- New message
     ELSE 0 -- Message has been read
 END;

当我执行此操作时,我返回以下内容:

enter image description here

正如你可以看到它是同一个用户,区别在于我有一个NewMessage,即1导致该用户出现两次,如果我在查询中删除case语句,那么我得到一行但我不会#39;我知道我是否有新消息。我试图让这个查询只返回1行,并且NewMessage的状态为1或0,这取决于我是否有新消息。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

在评论中我们的谈话后,我认为这将为您提供您正在寻找的结果:

<title>{{::AppConfig.SITE_TITLE}} | {{::AppConfig.PAGE_TITLE}}</title>