简体   繁体   English

不与其他列一起使用

[英]distinct not working with other columns

I am trying to use distinct in my query 我正在尝试在查询中使用distinct

select distinct tvpAuditevent.TESTSEQUENCEID
from tvpAuditevent
where tvpAuditevent.Name = 'WorkstepCompleted';

it works fine. 它工作正常。 and give me only 100 Results 只给我100个结果

But now if I add other columns like this 但是现在如果我添加其他这样的列

select distinct tvpAuditevent.TESTSEQUENCEID, tvpAuditevent.USERNAME
from  tvpAuditevent
where tvpAuditevent.Name = 'WorkstepCompleted';

it gives me around 200 results, which is wrong. 它给了我大约200个结果,这是错误的。 I need to only those 100 results but need other columns as well other than testsequenceId. 我只需要这100个结果,但除了testsequenceId之外,还需要其他列。

Please let me know if there is a way to do this. 请让我知道是否有办法。

Thanks 谢谢

As explained in another answer, the distinct keyword applies to all the columns in the select statement. 如另一个答案所述, distinct关键字适用于select语句中的所有列。 You cannot limit it to just one column. 您不能将其限制为仅一列。

Instead, you can use group by along with an aggregation function. 相反,您可以将group by与聚合功能一起使用。 For instance, the following returns the minimum value from the second column: 例如,以下代码从第二列返回最小值:

select ae.TESTSEQUENCEID, min(ae.USERNAME)
from  tvpAuditevent ae
where ae.Name = 'WorkstepCompleted'
group by ae.TESTSEQUENCEID;

In fact, the distinct keyword in a select is just a notational convenience. 实际上, selectdistinct关键字只是一种符号上的方便。 The following: 下列:

select distinct col1, col2, . . ., coln
from table t

does the same thing as: 与以下功能相同:

select col1, col2, . . . coln
from table t
group by col1, col2, . . . coln

The keyword DISTINCT will simply remove duplicate results from the result set. 关键字DISTINCT只会从结果集中删除重复的结果。 It cannot be applied to a single column when you are selecting multiple columns. 选择多个列时,不能将其应用于单个列。

What you want exactly is not clear. 您到底想要什么还不清楚。 Let's say we have the following data, where the first value is the column you want to be distinct, and the other the column you want to display as "extra data". 假设我们有以下数据,其中第一个值是您要区分的列,另一个值要显示为“额外数据”的列。

A,B
A,C

What should the result be? 结果应该是什么? A,B or A,C ? A,BA,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM