在select中使用distinct与多个表连接

时间:2017-03-09 12:29:57

标签: sql-server join distinct

尝试在select语句中使用Distinct但未获得所需的结果。我希望CaseID仅返回上次更新的评论。以下是我尝试使用的查询。

Select Distinct av.CaseID,fr.Rule_Description, av.Date, av.Status, fr.RULE_PRIORITY, ac.User_comments, max(ac.Comment_PostDate),ac.UserID
From tblAlertView av
Join tblAlertComment ac
on  av.CaseID = ac.CaseID
Join tblFBLRule fr
on  av.RuleID = fr.Rule_ID
Join TBLUSER usr
on ac.UserID = usr.USERID

group by av.CaseID, fr.Rule_Description, av.Date, av.Status, fr.RULE_PRIORITY, ac.User_comments, ac.Comment_PostDate,ac.UserID

Query Result

2 个答案:

答案 0 :(得分:0)

删除

ac.Comment_PostDate

来自group by子句

答案 1 :(得分:0)

如果您使用JOIN,而不是使用tblAlertComment转到CROSS APPLY,您可以指定只返回每个案例的前1个评论:

SELECT  av.CaseID, 
        fr.Rule_Description, 
        av.Date, 
        av.Status, 
        fr.RULE_PRIORITY, 
        ac.User_comments, 
        ac.Comment_PostDate,
        ac.UserID
FROM    tblAlertView AS av
        INNER JOIN tblFBLRule AS fr
            ON av.RuleID = fr.Rule_ID
        CROSS APPLY
        (   SELECT  TOP 1 ac.User_comments, ac.Comment_PostDate, ac.UserID
            FROM    tblAlertComment AS ac
                    INNER JOIN tblUser AS usr
                        ON usr.UserID = ac.UserID
            WHERE   ac.CaseID = av.CaseID
            ORDER BY ac.Comment_PostDate DESC
        ) AS ac;