簡體   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