繁体   English   中英

如果两个不同表中的两个相同列具有值,如何返回true? 的SQL

[英]How to return true if two same columns in two different tables have values? SQL

表_A 表_B

回到这里,再问一个大家!

因此,我们有两个数据透视表Table_A和Table_B。 两个表都有相同的列。

我试图编写一个查询,该查询将遍历每一行,并且仅当具有相同ID的记录在“值”字段中具有值时,才返回true。 因此,例如,对于记录ID3,Table_A具有“ sdnbfsj”值,而对于同一记录ID,Table_B在“值”字段下具有值。

该查询应该能够验证两个表中的相同单元格是否具有值,如果它们具有值,则返回true。 如果表总共只有三条记录,则返回true,但是请注意,记录ID 5在Table_A中有一个值,但记录ID 5在Table_B中为NULL。 因此查询应返回false。

这是我到目前为止的内容:

SELECT source_column from 
(
select source_column from Table_A WHERE Value_Inserted=1
EXCEPT
select source_column from Table_B WHERE Value_Inserted=1
)X
WHERE source_column  IN 
(
'Col_1'
,'COl_2'
,'Col_3'
,'Col_4'
)

通过首先在id上连接两个表,然后根据您的条件进行计数,您应该能够做到这一点。 然后...返回“ true”或“ false”

SELECT CASE WHEN SUM(CASE WHEN t1.value IS NOT NULL AND t2.value IS NOT NULL THEN 1 ELSE 0 END) = Count(*) THEN 'True' ELSE 'False' END as test
FROM table_a as t1
    INNER JOIN table_b as t2 ON
        t1.id = t2.id

语法可能会有所不同,具体取决于您使用的RDBMS。

我想你要:

select min(case when a.value is not null and a.value is null then 0
                when a.value is null a and a.value is not null then 0
                else 1
           end) as flag
from a join
     b
     on a.class = b.class and a.source_col = b.source_col;

这会将1视为true,将0视为false。

取决于您使用的DBMS

对于Oracle,请使用nvl2函数:

select nvl2(a.value, 1, 0) * nvl2(b.value, 1, 0)
  from Table_A a
 inner join Table_B b
    on (a.ID = b.ID);

对于MSSQL,可以使用convertcast函数:

select   convert(int, ( case when IsNull(a.value,'0') = '0' then '0' 
              else '1' 
         end ))
         *
         convert(int, ( case when IsNull(b.value,'0') = '0' then '0' 
              else '1' 
         end )) as result
  from Table_A a
 inner join Table_B b
    on (a.ID = b.ID);

对于MySQL,请使用IfNull函数:

select   ( case when IfNull(a.value,'0') = '0' then '0' 
              else '1' 
         end )
         *
         ( case when IfNull(b.value,'0') = '0' then '0' 
              else '1' 
         end ) as result
  from Table_A a
 inner join Table_B b
    on (a.ID = b.ID);

对于PostGreSQL,请使用coalesce函数:

select   cast( ( case when coalesce(a.value,'0') = '0' then '0' 
              else '1' 
         end ) as int )
         *
         cast( ( case when coalesce(b.value,'0') = '0' then '0' 
              else '1' 
         end ) as int ) as result
  from Table_A a
 inner join Table_B b
    on (a.ID = b.ID);

他们都给出以下结果

result
  0
  0
  1
  0
  0

暂无
暂无

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

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