【问题标题】:Teradata SQL and not vs andTeradata SQL 而不是 vs 和
【发布时间】:2018-02-12 16:06:54
【问题描述】:

我有一张要拆分的表。

原始表有 1,390k 行,我想使用三个条件 A、B 和 C 来拆分表。

此查询返回 60k 行

sel stuff
from table
where  ( A and C)
and (B and C) 

此查询返回 1,060k 行:

sel stuff
from table
where  not ( A and C)
and not (B and C) 

我的问题是为什么第二个查询返回 1,060k 行,而不是我预期的 1,330k?

【问题讨论】:

  • 如果where not ( ( A and C) and (B and C))
  • 任何空值?
  • @JaydipJ 这个逻辑没有返回任何东西。
  • @jarlh 不,数据中没有空值。
  • create table tb (a boolean, b boolean, c boolean) 添加数据(所有 8 种组合)。试试你的查询!

标签: sql teradata


【解决方案1】:

x and y 的反义词是not x OR not y

【讨论】:

  • not x OR not y 产生的行为与我在问题中的第二个查询相同
  • 确实没有空值?好的,查看所涉及的列的实际查询和数据类型真的很有帮助......并确认您测试的是not (a and c) or not(b and c)。加上您的第一个查询的逻辑等价物:a and c and b
【解决方案2】:

(A & C) & (B & C) 的反义词不是!(A & C) & !(B & C),而是!((A & C) & (B & C))

由于没有共享示例数据,我假设您的表具有如下示例数据。

a   b   c
---------
0   0   0
1   0   0
0   1   0
0   0   1
1   1   0
0   1   1
1   0   1
1   1   1

您的原始查询如下

select * from t1
where ( A=1 and C=1)
and (B=1 and C=1);

结果 1:

a   b   c
---------
1   1   1

您建议生成与上述查询相反的结果的查询如下,永远不会产生您想要的结果。

select * from t1
where not(A=1 and C=1)
and not(B=1 and C=1);

结果 2:

a   b   c
---------
0   0   0
1   0   0
0   1   0
0   0   1
1   1   0

以下任何查询都会生成与原始查询相反的结果。

select * from t1
where not(( A=1 and C=1)
and (B=1 and C=1));

select * from t1
where A<>1 or B<>1 or C<>1;

结果 3:

a   b   c
---------
0   0   0
1   0   0
0   1   0
0   0   1
1   1   0
0   1   1
1   0   1

从上面的查询结果可以看出,result 1result 3 正好相反。您可以查看演示here

【讨论】:

  • 或者简单地说:where A&lt;&gt;1 or B&lt;&gt;1 or C&lt;&gt;1 :-)
  • @dnoeth:没错,一如既往,直观:-)
【解决方案3】:

我看到这已经有了答案。不过,我认为值得一提的方法是不需要您过多思考原始查询的逻辑逆是什么。

如果第二个查询的目标只是获取第一个查询中没有的所有内容,那么您的第二个查询应该是这样的:

sel stuff --This part gets the new records
from table
Minus --This part is the original query and excludes those records
sel stuff
from table
where  ( A and C)
and (B and C) 

【讨论】:

    猜你喜欢
    • 2022-02-23
    • 2011-04-12
    • 2021-12-17
    • 2016-11-03
    • 2017-01-06
    • 2014-11-21
    • 2016-02-22
    • 1970-01-01
    • 2014-07-01
    相关资源
    最近更新 更多