[英]SELECT DISTINCT with two columns
我需要區分SenderId
和RecipientId
。
所以我這樣做:
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
但這是行不通的。
這里有一些選擇; 從最適合您要求的措詞中不確定,但是懷疑有人會...
--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
如果我已正確理解您的問題,則它將對您想要的內容進行分組,並區分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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.