[英]distinct not working with other columns
我正在尝试在查询中使用distinct
select distinct tvpAuditevent.TESTSEQUENCEID
from tvpAuditevent
where tvpAuditevent.Name = 'WorkstepCompleted';
它工作正常。 只给我100个结果
但是现在如果我添加其他这样的列
select distinct tvpAuditevent.TESTSEQUENCEID, tvpAuditevent.USERNAME
from tvpAuditevent
where tvpAuditevent.Name = 'WorkstepCompleted';
它给了我大约200个结果,这是错误的。 我只需要这100个结果,但除了testsequenceId之外,还需要其他列。
请让我知道是否有办法。
谢谢
如另一个答案所述, distinct
关键字适用于select
语句中的所有列。 您不能将其限制为仅一列。
相反,您可以将group by
与聚合功能一起使用。 例如,以下代码从第二列返回最小值:
select ae.TESTSEQUENCEID, min(ae.USERNAME)
from tvpAuditevent ae
where ae.Name = 'WorkstepCompleted'
group by ae.TESTSEQUENCEID;
实际上, select
的distinct
关键字只是一种符号上的方便。 下列:
select distinct col1, col2, . . ., coln
from table t
与以下功能相同:
select col1, col2, . . . coln
from table t
group by col1, col2, . . . coln
关键字DISTINCT
只会从结果集中删除重复的结果。 选择多个列时,不能将其应用于单个列。
您到底想要什么还不清楚。 假设我们有以下数据,其中第一个值是您要区分的列,另一个值要显示为“额外数据”的列。
A,B
A,C
结果应该是什么? A,B
或A,C
吗?
SELECT S.TESTSEQUENCEID,
AE.tvpAuditevent.USERNAME
FROM tvpAuditevent AE
JOIN (select distinct tvpAuditevent.TESTSEQUENCEID
from tvpAuditevent where tvpAuditevent.Name = 'WorkstepCompleted' ) S
ON S.TESTSEQUENCEID = AE.TESTSEQUENCEID
where AE.tvpAuditevent.Name = 'WorkstepCompleted'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.