I have the following tables:
create table Invoices
(
InvoiceID int,
InvoiceNumber int,
InvoiceDate date,
SupplierName varchar(250),
SupplierCode varchar(20),
InvoiceValue decimal(18,2)
);
insert into Invoices (InvoiceID, InvoiceNumber, InvoiceDate, SupplierName, SupplierCode, InvoiceValue) values
(1,700,'2021-01-01','ACME','A01',978.32),
(2,701,'2021-01-02','MACROD','A02',772.81),
(3,702,'2021-01-03','CODECO','A03',938.20),
(4,703,'2021-01-04','ACME','A03',892.18),
(5,704,'2021-01-05','CODECO','A03',791.41),
(6,705,'2021-01-06','DRONIX','A04',469.03);
create table Payments
(
InvoiceID int,
PaymentDate date,
PaymentValue decimal(18,2)
);
insert into Payments (InvoiceID, PaymentDate, PaymentValue) values
(1, '2021-01-11', 500.00),
(1, '2021-01-12', 50.00),
(1, '2021-02-13', 100.00),
(3, '2021-02-14', 10.00),
(4, '2021-03-15', 200.00),
(3, '2021-03-16', 300.00),
(5, '2021-04-17', 75.00),
(1, '2021-04-18', 30.00);
This is the query I'm using:
SELECT
a.SupplierName,
a.SupplierCode,
SUM(a.TotalInvoiceValue),
ISNULL(SUM(b.PaidAmount), 0),
SUM(a.TotalInvoiceValue) - ISNULL(SUM(b.PaidAmount), 0)
FROM (
SELECT
InvoiceID,
SupplierName,
SupplierCode,
SUM(InvoiceValue) AS TotalInvoiceValue
FROM Invoices
WHERE InvoiceDate BETWEEN '2021-01-01 00:00:00' AND '2021-01-31 23:59:29'
GROUP BY
InvoiceID,
SupplierName,
SupplierCode
) a
LEFT JOIN (
SELECT
InvoiceID,
ISNULL(SUM(PaymentValue),0) AS PaidAmount
FROM Payments
GROUP BY InvoiceID
) b
ON a.InvoiceID=b.InvoiceID
GROUP BY
a.InvoiceID,
a.SupplierName,
a.SupplierCode
ORDER BY
a.SupplierName
The query above is returning multiple rows for the same SupplierName from Payments table.
I'm using Microsoft SQL Server 2005.
See the SQL fiddle here
VALUEStable construct was introduced in SQL Server 2008.left joinand replace it with a window aggregate on the first tableISNULL(SUM(SUM(b.PaidAmount)) OVER (PARTITION BY InvoiceID), 0)