我有超过 1 个表,例如 INVOICE、PAYMENT、RETURN_INVOICE、RETURN_PAYMENT 等。我想检索每个客户的数据 CREDIT、DEBIT 和 BALANCE
下面是表和插入查询语句,
CREATE TABLE Customer
(
CustomerId INT IDENTITY(1,1),
RegistrationDate DATE,
CustomerName VARCHAR(45),
OpeningBalance MONEY,
PRIMARY KEY(CustomerId)
)
INSERT INTO Customer (CustomerName, RegistrationDate, OpeningBalance) VAlUES ('JOHN', '2020-01-15', 1000)
CREATE TABLE Invoice
(
InvoiceId INT IDENTITY(1,1),
InvoiceDate DATE,
CustomerId INT,
InvoiceTotal MONEY,
PRIMARY KEY(InvoiceId)
)
INSERT INTO Invoice (InvoiceDate, CustomerId, InvoiceTotal) VAlUES ('2020-01-16', 1, 2000)
INSERT INTO Invoice (InvoiceDate, CustomerId, InvoiceTotal) VAlUES ('2020-01-17', 1, 500)
INSERT INTO Invoice (InvoiceDate, CustomerId, InvoiceTotal) VAlUES ('2020-01-17', 1, 250)
INSERT INTO Invoice (InvoiceDate, CustomerId, InvoiceTotal) VAlUES ('2020-01-20', 1, 1000)
INSERT INTO Invoice (InvoiceDate, CustomerId, InvoiceTotal) VAlUES ('2020-01-22', 1, 2250)
INSERT INTO Invoice (InvoiceDate, CustomerId, InvoiceTotal) VAlUES ('2020-01-24', 1, 1750)
INSERT INTO Invoice (InvoiceDate, CustomerId, InvoiceTotal) VAlUES ('2020-01-28', 1, 3000)
CREATE TABLE Payment
(
PaymentId INT IDENTITY(1,1),
PaymentDate DATE,
CustomerId INT,
PaymentTotal MONEY,
PRIMARY KEY(PaymentId)
)
INSERT INTO Payment (PaymentDate, CustomerId, PaymentTotal) VAlUES ('2020-01-18', 1, 750)
INSERT INTO Payment (PaymentDate, CustomerId, PaymentTotal) VAlUES ('2020-01-20', 1, 2000)
INSERT INTO Payment (PaymentDate, CustomerId, PaymentTotal) VAlUES ('2020-01-23', 1, 5000)
INSERT INTO Payment (PaymentDate, CustomerId, PaymentTotal) VAlUES ('2020-01-26', 1, 200)
INSERT INTO Payment (PaymentDate, CustomerId, PaymentTotal) VAlUES ('2020-01-28', 1, 500)
CREATE TABLE ReturnInvoice
(
ReturnInvoiceId INT IDENTITY(1,1),
ReturnInvoiceDate DATE,
CustomerId INT,
ReturnInvoiceTotal MONEY,
PRIMARY KEY(ReturnInvoiceId)
)
INSERT INTO ReturnInvoice (ReturnInvoiceDate, CustomerId, ReturnInvoiceTotal) VAlUES ('2020-01-25', 1, 500)
INSERT INTO ReturnInvoice (ReturnInvoiceDate, CustomerId, ReturnInvoiceTotal) VAlUES ('2020-01-28', 1, 300)
INSERT INTO ReturnInvoice (ReturnInvoiceDate, CustomerId, ReturnInvoiceTotal) VAlUES ('2020-01-29', 1, 1000)
CREATE TABLE ReturnPayment
(
ReturnPaymentId INT IDENTITY(1,1),
ReturnPaymentDate DATE,
CustomerId INT,
ReturnPaymentTotal MONEY,
PRIMARY KEY(ReturnPaymentId)
)
INSERT INTO ReturnPayment (ReturnPaymentDate, CustomerId, ReturnPaymentTotal) VAlUES ('2020-01-21', 1, 500)
INSERT INTO ReturnPayment (ReturnPaymentDate, CustomerId, ReturnPaymentTotal) VAlUES ('2020-01-27', 1, 2000)
我想像这样检索输出,
- 所有表都应该是客户的内部连接(CustomerId 是外键)
- 需要检索额外的列Description并提及表事务名称和No.(上图中的第3列)
- 客户OPENING BALANCE应位于客户表的顶部行
- 按日期排序,其下没有。
如何获得上图中的预期输出。