我有两个列表要比较。一个是最近45天内付款的客户列表,第二个是最近12个月内付款的客户
查询1
select i.trandate, i.tranid, c.companyname, c.customer_id, tl.amount
, '12 Mo Customers' 'Type'
from ns.tpayment i
join ns.Customers c on c.customer_id = i.ENTITY_ID
join ns.transaction_lines tl on i.transaction_id = tl.transaction_id
join ns.accounts a on a.account_id = tl.account_id
where a.name = 'General Checking' and DATEDIFF(month,i.trandate, GETDATE()) <= 12
查询2
select i.trandate, i.tranid, c.companyname, c.customer_id, tl.amount
, '45 Day Customers' 'Type'
from ns.tpayment i
join ns.Customers c on c.customer_id = i.ENTITY_ID
join ns.transaction_lines tl on i.transaction_id = tl.transaction_id
join ns.accounts a on a.account_id = tl.account_id
where a.name = 'General Checking' and DATEDIFF(day,i.trandate, GETDATE()) <= 45
我需要将第一个查询生成的列表与第二个查询生成的列表进行比较,以查看谁在最近12个月内付款了,但在最近45天内没有付款。
下一步有些困难,希望有人对如何在单个查询中最好地完成这一想法有所了解。
答案 0 :(得分:2)
您可以使用聚合和having
子句:
select c.companyname, c.customer_id
from ns.tpayment i join
ns.Customers c
on c.customer_id = i.ENTITY_ID join
ns.transaction_lines tl
on i.transaction_id = tl.transaction_id join
ns.accounts a
on a.account_id = tl.account_id
where a.name = 'General Checking' and
DATEDIFF(month, i.trandate,
GETDATE()) <= 12
group by c.companyname, c.customer_id
having DATEDIFF(day, max(i.trandate), GETDATE()) > 45;