简体   繁体   English

SQL Server-查找唯一记录

[英]SQL Server - Find Unique Records

I am trying and failing to write a script to return any unique combinations of job and suffix where the (oper = 20 and value = 0) and (oper > 20 and value = 1). 我正在尝试并且未能编写脚本来返回作业和后缀的任何唯一组合,其中(oper = 20且值= 0)和(oper> 20且值= 1)。 Based on the data below there is only one instance, job 2 suffix 3. In this combination of job and suffix the oper 20 = 0 and the oper 40 = 1. 根据下面的数据,只有一个实例,作业2后缀3。在作业和后缀的这种组合中,操作员20 = 0,操作员40 = 1。

job suffix oper value

1    1       20    0

1    1       30    0

2    3       20    0

2    3       40    1

3    2       20    0

3    3       50    1

Any help would be appreciated 任何帮助,将不胜感激

SELECT job
     , suffix
FROM t1
GROUP BY job
       , suffix
HAVING COUNT(CASE WHEN (oper = 20 and value = 0) OR (oper > 20 and value = 1) THEN suffix END) =  COUNT(*) 
   AND COUNT(*) = 2

Example

One way to approach this is as a "set-within-sets" subquery. 解决此问题的一种方法是使用“组内设置”子查询。 A flexible approach to solving these is using group by and having . 解决这些问题的一种灵活方法是使用group byhaving In your case: 在您的情况下:

select t.job, t.suffix
from table t
group by t.job, t.suffix
having sum(case when oper = 20 and value = 0 then 1 else 0 end) > 0 and
       sum(case when oper > 20 and value = 1 then 1 else 0 end) > 0;

Each condition in the having clause counts the number of rows that match a specific condition. 中每个条件having子句计数匹配特定条件的行的数目。 So, the first ensure that there is at least one row where oper = 20 and value = 0 . 因此,首先要确保至少有一行oper = 20 and value = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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