SELECT DISTINCT有两列

时间:2014-07-15 21:33:49

标签: sql sql-server select group-by distinct

我需要区分SenderIdRecipientId

所以我这样做了:

SELECT DISTINCT M.SenderId, R.StudentId as RecipientId
FROM Message M (nolock) INNER JOIN Recipient R (nolock) ON M.Id=R.MessageId 
GROUP BY M.SenderId, R.StudentId
HAVING StudentId=1 OR SenderId=1

这有效,但我还需要M.Text字段,但没有不同。 所以我补充说:

GROUP BY M.SenderId, R.StudentId, M.Text

但这不起作用。

2 个答案:

答案 0 :(得分:2)

这里有一些选择;不能确定最适合您要求的措辞,但怀疑会有......

--selects unique combination of sender, recipient and text
--meaning the combo of 3 is unique, but within that combo values
--in each individual column may be repeated

SELECT DISTINCT M.SenderId
, R.StudentId as RecipientId
, M.Text
FROM Message M (nolock) 
INNER JOIN Recipient R (nolock) ON R.MessageId = M.Id
where StudentId=1 
or SenderId=1

--returns all unique combos of SenderId and RecipientId
--along with a single corresponding Text field
--max() is just an arbitrary aggregate function to ensure we only
--get 1 result for M.Text

SELECT M.SenderId
, R.StudentId as RecipientId
, max(M.Text)
FROM Message M (nolock) 
INNER JOIN Recipient R (nolock) ON R.MessageId = M.Id
where StudentId=1 
or SenderId=1
group bu M.SenderId
, R.StudentId 

答案 1 :(得分:0)

如果我已正确理解您的问题,这会将您想要的内容和不同的SenderId和StudentId分组:

SELECT M.SenderId, R.StudentId as RecipientId, M.Text
FROM Message M (nolock) INNER JOIN Recipient R (nolock) ON M.Id=R.MessageId 
GROUP BY M.SenderId, R.StudentId, M.Text
HAVING COUNT(StudentId) = 1 OR COUNT(SenderId) = 1