[英]SQL Server - Query to return ID's only which have different values per ID in another column
SQL Server 2016 Enterprise - Let's say I run a query on our main table to bring back all records from ID's 1 through 5. I would get something like this: SQL Server 2016企业版-假设我在主表上运行查询以从ID的1到5取回所有记录。我会得到如下信息:
ID Status BatchID
1 Active 493fd8bc
1 Active 493fd8bc
1 Active 493fd8bc
1 Active 493fd8bc
1 Active 493fd8bc
2 Active 2d91c2f2
2 Active 2d91c2f2
3 Active 2a1338ac
3 Active 2a1338ac
3 Active 2a1338ac
4 Active 0c469bcc
4 Active 0c469bcc
4 Active 0c469bcc
4 Active 0c469bcc
4 Active 0c469bcc
4 Active 0c469bcc
4 Active 0c469bcc
5 Active ca8896bd
5 Active ca8896bd
5 Active ca8896bd
The above is what we would expect to see, such that each ID
has the same BatchID
associated with it (additional columns that differentiate each record are irrelevant to this question). 上面是我们希望看到的结果,以便每个
ID
都具有BatchID
关联的相同BatchID
(区分每个记录的其他列与该问题无关)。
We've run into some issues where we are seeing this is not the case for all ID's
. 我们遇到了一些问题,我们发现并非所有
ID's
都有这种情况。 For example let's say we ran the same query and it returned this instead: 例如,假设我们运行了相同的查询,并返回了以下查询:
ID Status BatchID
1 Active 493fd8bc
1 Active 493fd8bc
1 Active 752e8d5d
1 Active 752e8d5d
1 Active 493fd8bc
2 Active 2d91c2f2
2 Active 2d91c2f2
3 Active f2191595
3 Active 2a1338ac
3 Active 2a1338ac
4 Active feaf9567
4 Active f5d64c8c
4 Active e5eff3a2
4 Active 0c469bcc
4 Active 49e5e2f2
4 Active 0c469bcc
4 Active e5eff3a2
5 Active ca8896bd
5 Active ca8896bd
5 Active ca8896bd
In this case we see that ID's
1, 3, and 4's BatchID
do NOT all match. 在这种情况下,我们看到
ID's
1、3和4的BatchID
并不完全匹配。
If I wanted to run a query on all ID's
and have it return to me a list of ID's
whose BatchID's
do NOT match for all records of that ID
, how would I accomplish this? 如果我想对所有
ID's
进行查询,并让我返回ID's
列表,而该ID's
BatchID's
与该ID
所有记录都不匹配,我该怎么做?
The results would look like this if my table contained only the data in the 2nd example above. 如果我的表仅包含上面第二个示例中的数据,则结果将看起来像这样。
ID
1
3
4
Alternatively, we'd be just as well-suited if the results were returned as entire records as long as the record contains the ID
, and there is only one record per ID
. 另外,只要记录包含
ID
,并且返回的结果是完整记录,并且每个ID
仅包含一条记录,我们也会非常适合。 The BatchID
returned is of no consequence. 返回的
BatchID
。
Use aggregation and count the number of distinct batches for each ID
: 使用汇总并为每个
ID
计算不同批次的数量:
SELECT ID
FROM yourTable
GROUP BY ID
HAVING COUNT(DISTINCT BatchID) > 1;
If you happen to want the entire row, you can do: 如果您碰巧想要整行,则可以执行以下操作:
select t.*
from t
where exists (select 1
from t t2
where t2.id = t.id and t2.batchid <> t.batchid
);
If you just want the ids, then Tim's answer is the better approach. 如果只需要ID,Tim的答案就是更好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.