简体   繁体   中英

SQL: Find all records in Table A that do not have a value in Table B based on a column value in Table B

Using Microsoft SQL Server 2012, I'm trying to get all businesses who did not make a payment in 2016.

Here is my schema

Business Table
---------------
Id     Name
1      Business A
2      Business B

Payments Table
---------------
Id     BusinessId   Year
1      2            2016
2      1            2017
3      2            2017

I need a SQL statement that returns Business A since it does not have a payment for 2016.

Here is what I have tried:

SELECT [Business].Name
FROM Businesses as [Business]            
Left Outer JOIN Payments as [Payment]
     ON [Payment].BusinessId = [Business].Id
Where [Business].Id is null and [Payment].TaxYear = 2016

Any help would be greatly appreciated.

Also, the title might be a little convoluted, so a suggested edit for the title of this question would be welcome as well.

NOT EXISTS, should return Business A since it does not have a 2016 transaction

SELECT B.Name
FROM Business as B            
WHERE NOT EXISTS (    
  SELECT 1 FROM Payments P
Where P.TaxYear = 2016
     AND P.BusinessId = B.Id )

I think you are looking for the combination of businesses and years that are not in the payments table. If so:

select b.*
from businesses b cross join
     (select distinct year from payments) y left join
     payments p
     on b.id = p.businessid and b.year = y.year
where p.businessid is null;

The cross join generates all combinations of businesses and years. The left join and where clause then finds the ones that don't exist.

If you are only looking for one year, then @maSTAShuFu answer is the correct approach.

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