SQl查询以获取唯一记录

时间:2015-06-11 16:16:37

标签: sql-server

我有以下数据:

pdtid  version  col1 col2 col3

1        1       0     0   0
1        2       0     0   0
1        3       0     0   0 
2        1       0     0   0
2        2       1     1   0
3        1       0     0   0
4        1       0     0   0
4        2       0     1   0

当符合条件pdtidcol1 = 0col2 = 0时,如何编写返回col3 = 0 1和3的查询?

修改pdtid只应在{strong>所有记录pdtid符合条件col1=0 and col2=0 and col3=0

时返回

在此示例中,结果应返回pdtid 1和3,但不返回2,因为2包含不符合条件的记录。

4 个答案:

答案 0 :(得分:3)

这不是写一个普通的SELECT语句那么简单吗?

SELECT  pdtid
  FROM  table
  WHERE col1 = 0 AND
        col2 = 0 AND
        col3 = 0

或者,如果您只想要不同的条目,请添加DISTINCT子句:

SELECT  DISTINCT pdtid
  FROM  table
  WHERE col1 = 0 AND
        col2 = 0 AND
        col3 = 0

修改

在澄清您希望仅pdtid col1col2col3为{0}的所有version时才返回SUM,请参阅下方。

尝试以下内容,它应该向您展示如何使用嵌套表实现此目的,SELECT之前CREATE TABLE #table (pdtid INT, [version] INT, col1 INT, col2 INT, col3 INT) INSERT INTo #table (pdtid, [version], col1, col2, col3) VALUES (1, 1, 0, 0, 0), (1, 2, 0, 0, 0), (1, 3, 0, 0, 0), (2, 1, 0, 0, 0), (2, 2, 1, 1, 0), (3, 1, 0, 0, 0), (4, 1, 0, 0, 0), (4, 2, 0, 1, 0) SELECT pdtid FROM ( SELECT pdtid, SUM(col1) AS col1, SUM(col2) AS col2, SUM(col3) AS col3 FROM #table GROUP BY pdtid) a WHERE a.col1 = 0 AND a.col2 = 0 AND a.col3 = 0 DROP TABLE #table 每个列的值为UIButton

image.png

答案 1 :(得分:1)

这是 关系部门,没有剩余(RDNR) 问题。请参阅Dwain Camps的article,为这类问题提供了许多解决方案。

SELECT t.ptid
FROM Test t
WHERE 
    t.col1 = '0'
    AND t.col2 = '0'
    AND t.col3 = '0'
GROUP BY t.ptid
HAVING 
    COUNT(*) = (SELECT COUNT(*) FROM Test WHERE ptid = t.ptid)

答案 2 :(得分:0)

可以使用相关的子查询。

 SELECT  pdtid
      FROM table A
      WHERE col1 = 0 and col2=0 and col3 = 0
     and not exists (Select 1 
                     from table B 
                     where A.pdtid=b.pdtid AND 
                           (col1<> 0 or col2 <> 0 or col3 <> 0)

基本上,这会生成一组数据,其中col1,2,3不为0,并且仅表示返回0的记录,而不是定义为0的集合。

或......作为联接

SELECT  A.pdtid
FROM foo A
LEFT JOIN (Select pdtid
           from foo B 
           where B.col1+B.col2+B.col3 <> 0)  B
on A.pdtid=B.pdtid
WHERE A.col1+A.col2 +A.col3 = 0
and B.pdtid is null
group by A.pdtid

工作fiddle

但如果我们想简单地使用where子句而不是总结值...... Fiddle

SELECT  A.pdtid
FROM foo A
LEFT JOIN (Select pdtid
           from foo B 
           where B.col1<> 0 or B.col2 <> 0 or B.col3 <> 0)  B
on A.pdtid=B.pdtid
WHERE A.col1=0 AND A.col2=0 AND A.col3 = 0
and B.pdtid is null
group by A.pdtid

答案 3 :(得分:0)

通用解决方案使用GROUP BY / HAVING:

select pdtid
from tab
group by pdtid
having max(case when col1 = 0 then 0 else 1 end) = 0 -- returns 1 for any other value
   and max(case when col2 = 0 then 0 else 1 end) = 0
   and max(case when col3 = 0 then 0 else 1 end) = 0

或NOT EXISTS:

select distinct pdtid
from tab as t1
where not exists
 ( select *
   from tab as t2
   where t1.pdtid = t2.pdtid 
     and (col1 <> 0 or col2 <> 0 or col3 <> 0) -- might not work correctly when NULLs exist
 )