简体   繁体   中英

SQL Server - How to check if a value does not exist in other rows of the same table for same column values?

Following are the two tables in SQL Server: TABLE_A and TABLE_B

在此处输入图片说明

I need to get the output as follows:

  • Get IDs from TABLE_A where Exist = 0

    We would get 100, 101 & 102

  • Now, among 100, 101 & 102, no other rows (in the same table) with the same ID value should have Exist = 1

    Hence, 100 can't be selected as it has Exist = 1 in the 2nd row.

    So, only 101 & 102 remain

  • With the remaining ID values (101 & 102), check against the ID column in TABLE_B where 'Exist' column value should not be equal to '1' in any of the rows

    In TABLE_B, 4th row has Exist = 1 for 102. So, that can't be selected

    We have only 101 now. This is required output and that should be selected.

Could you let me know how to write the simplest query to achieve this please? Let me know if the question needs to be improved.

Try:

SELECT
    ID,
    SUM(CAST(Exist AS int)) AS [Exists]
FROM
    TABLE_A
GROUP BY ID
HAVING SUM(CAST(Exist AS bit)) = 0

will give you the answer to the first part. You can then JOIN this to a similar query for TABLE_B . That is a "simple" way to show how this works. You can write more complex queries as that from @Yogest Sharma

You can use exists & not exists :

with t as (
     select t1.*
     from t1
     where exists (select 1 from t1 t11 where t11.id = t1.id and t11.exists = 0) and
           not exists (select 1 from t1 t11 where t11.id = t1.id and t11.exists = 1)
)

select t.*
from t
where not exists (select 1 from t2 where t.id = t2.id and t2.exists = 1);

Like @Peter Smith mentioned, you can use the aggregate function SUM. Note that you would need a cast since you cannot use the aggregate function on a field that has a BIT datatype

;WITH CTE AS
(
SELECT ID, SUM(CAST(Exist AS INT)) AS AggExist FROM TABLE_A GROUP BY ID
UNION
SELECT ID, SUM(CAST(Exist AS INT)) As AggExist FROM TABLE_B GROUP BY ID
)
SELECT ID, SUM(AggExist) FROM CTE GROUP BY ID
HAVING SUM(AggExist) = 0

Here is the demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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