[英]SQL Trigger to copy value from Table A - Column A to Table B - Column A IF Value is unique in Table B
[英]SQL: Find all records in Table A that do not have a value in Table B based on a column value in Table B
我正在嘗試使用Microsoft SQL Server 2012獲取所有在2016年未付款的企業。
這是我的圖式
Business Table
---------------
Id Name
1 Business A
2 Business B
Payments Table
---------------
Id BusinessId Year
1 2 2016
2 1 2017
3 2 2017
我需要一條返回業務A的SQL語句,因為它沒有2016年的付款。
這是我嘗試過的:
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
任何幫助將不勝感激。
同樣,標題可能有點令人費解,因此也歡迎對此問題的標題進行建議的編輯。
不存在,應返回業務A,因為它沒有2016年的交易
SELECT B.Name
FROM Business as B
WHERE NOT EXISTS (
SELECT 1 FROM Payments P
Where P.TaxYear = 2016
AND P.BusinessId = B.Id )
我認為您正在尋找付款表中沒有的業務和年份的組合。 如果是這樣的話:
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;
cross join
生成業務和年份的所有組合。 然后, left join
和where
子句查找不存在的聯接。
如果您只尋找一年,那么@maSTAShuFu答案是正確的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.