[英]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.