从表中选择不同的行

时间:2016-05-13 14:26:06

标签: sql sql-server-2008

我有一个主表(AllDocs),我运行了一个查询,它给了我145条记录。这很好。但是,有一些字段(如listid和userid)所以我决定从2个不同的表中获取listid和userid的标题。现在,我的结果是1870年。我尝试将distinct添加到select并将其减少到1530.行数应为145.我做错了什么?

SELECT DISTINCT AllDocs.SiteId, AllDocs.LeafName, AllDocs.ListId,
                AllDocs.CheckoutUserId, AllDocs.CheckoutDate,
                UserInfo.tp_Title AS [User Name], UserInfo.tp_Login AS [User ID], 
                UserInfo.tp_Email, AllLists.tp_Title AS [List Name]
FROM AllDocs
LEFT OUTER JOIN UserInfo ON AllDocs.CheckoutUserId = UserInfo.tp_ID
LEFT OUTER JOIN AllLists ON AllDocs.ListId = AllLists.tp_ID
WHERE (AllDocs.SiteId = 'E2FF98A7-B719-428D-8C30-856F08989691')
  AND (AllDocs.CheckoutUserId IS NOT NULL)    

1 个答案:

答案 0 :(得分:0)

尝试使用group by语句。其他行很可能会在查询中返回。

SELECT AllDocs.SiteId, AllDocs.LeafName, AllDocs.ListId,
   AllDocs.CheckoutUserId, AllDocs.CheckoutDate,
   UserInfo.tp_Title AS [User Name], UserInfo.tp_Login AS [User ID], 
            UserInfo.tp_Email, AllLists.tp_Title AS [List Name]
FROM AllDocs
LEFT OUTER JOIN UserInfo ON AllDocs.CheckoutUserId = UserInfo.tp_ID
LEFT OUTER JOIN AllLists ON AllDocs.ListId = AllLists.tp_ID
WHERE (AllDocs.SiteId = 'E2FF98A7-B719-428D-8C30-856F08989691')
 AND (AllDocs.CheckoutUserId IS NOT NULL)
Group by AllDocs.SiteId, AllDocs.LeafName, AllDocs.ListId,
   AllDocs.CheckoutUserId, AllDocs.CheckoutDate, UserInfo.tp_Title UserInfo.tp_Login,  UserInfo.tp_Email, AllLists.tp_Title