我有2张桌子,像这样:
租赁
ID,LeaseDate
租赁发票
ID,LeaseID,InvoiceDate,StartDate
如何查找所有LeaseDate与第一个StartDate的发票的InvoiceDate不匹配的情况?
我不知道该怎么做,这是怎么回事?
SELECT * FROM LeaseInvoice
INNER JOIN Leases ON Leases.ID = LeaseInvoices.LeaseID
WHERE LeaseDate IS NULL
OR LeaseDate <> (
SELECT TOP 1 InvoiceDate FROM LeaseInvoices
ORDER BY StartDate DESC
)
答案 0 :(得分:1)
您可以为此使用ROW_NUMBER()
函数,例如:
SELECT
ID
, LeaseDate
, InvoiceDate
, StartDate
FROM
(
SELECT
L.ID
, L.LeaseDate
, I.InvoiceDate
, I.StartDate
, ROW_NUMBER() OVER (PARTITION BY L.ID ORDER BY I.StartDate) R
FROM
Leases L
JOIN LeaseInvoices I ON L.ID = I.LeaseID
) Q
WHERE
R = 1
AND LeaseDate <> InvoiceDate