Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择带有两列的DISTINCT_Sql_Sql Server_Select_Group By_Distinct - Fatal编程技术网

Sql 选择带有两列的DISTINCT

Sql 选择带有两列的DISTINCT,sql,sql-server,select,group-by,distinct,Sql,Sql Server,Select,Group By,Distinct,我需要区分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.Te

我需要区分
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


如果我正确理解了您的问题,这将分组您想要的内容,并区分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

每个不同的M.发送者R.StudentId是否可以有多个M.文本?如果是,您希望选择哪一个?添加了
sql server
标记,因为
(nolock)
关键字使用
distinct
groupby
没有意义您不需要
distinct
groupby
。您也可以使用
WHERE
而不是
have
@djikay,您不需要选择列就可以在组中使用它,因为“max(M.Text)”不起作用获取长度大于与这两个ID相关的其他ID的文本,而不是相对于最近ID的文本row@FelipeSkinner; 它的工作取决于需求是什么。您指的是第二个SQL。对于每个不同的发件人/收件人组合,它将从与该发件人/收件人组合相关联的组合中返回单个任意(最大)message.text值。@FelipeSkinner关于您对长度的评论;这是没有逻辑的-应用于字符串(varchar等)的最大值在按字母顺序排序时给出最后一个值(即给定'AAA','B'它将返回'B';给定'AAA','a'它将返回'AAA')。可能是因为我使用“car”和“hello”进行了测试,所以我假设是这样。这是我的错,因为我认为这篇文章不是武断的,而是最新的one@FelipeSkinner在上述情况下{2,3}和{3,2}是不同的,因为它们指的是发送者和接收者;i、 e.不同实体。如果这两个问题都是,比如说,messageParticipants,您可以使用以下内容来解释:-但是这将是一个与上面不同的问题,因此应该在这里作为一个新问题提问。
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