2014-07-15 83 views
0

我需要清除SenderIdRecipientIdSELECT DISTINCT with two columns

所以我這樣做:

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 

但是這不起作用。

+3

對於每個不同的M.Sender,R.StudentId是否可以有多個M.Text?如果是的話,你想選擇哪一個? –

+0

由於'(nolock)'關鍵字添加了'sql-server'標籤 –

+0

使用'distinct' **和**'group by'沒有意義 –

回答

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 
+0

這是行不通的,因爲「max(M.Text)」得到的文本長度大於其他與這兩個ID相關的文本,而不是相對於最近行的文本 –

+0

@FelipeSkinner;它的工作取決於需求是什麼。你指的是第二個SQL。對於每個不同的發件人/收件人組合,它將返回與發件人/收件人組合關聯的任意(最大)message.text值。 – JohnLBevan

+1

@FelipeSkinner關於你對長度的評論;這是沒有邏輯 - 最大應用於一個字符串(varchar,等)價值提供最後一個值時,按字母順序排序(即給予'AAA','B'它會返回'B';給予'AAA','A'它會返回'AAA')。 – JohnLBevan

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