0

我遇到了数据库连接查询的问题,我正在寻找帮助我的人。

基本上我有两张表,发票和收据。

发票

Invoice ID
Amount
Date_Added

收据

ReceiptID
InvoiceID
Amount
Date_Added

问题是我需要生成一个如下所示的表格,但我在 Receipts 中有多个记录,我很确定数据以一种好的方式存储,只是不确定查询是什么。

InvoiceID   RecieptID    Amount     Balance     Date_Added
1           0            100.00     100.00      01.05.2012
1           1            100.00     0.00        02.05.2012
2           0            250.00     250.00      03.05.2012
3           0            100.00     350.00      04.05.2012
2           2            100.00     250.00      05.05.2012

这有意义吗?所以它应该按日期顺序排列。如此有效,我可以逐行查看每个日期的情况。

4

2 回答 2

2

设置:

USE tempdb;
GO

CREATE TABLE dbo.Invoices
(
  InvoiceID INT,
  Amount DECIMAL(12,2),
  DateAdded SMALLDATETIME
);

CREATE TABLE dbo.Receipts
(
  ReceiptID INT,
  InvoiceID INT,
  Amount DECIMAL(12,2),
  DateAdded SMALLDATETIME
);

SET NOCOUNT ON;

INSERT dbo.Invoices SELECT 1, 100, '20120501'
UNION ALL SELECT 2, 250, '20120503'
UNION ALL SELECT 3, 100, '20120504';

INSERT dbo.Receipts SELECT 1, 1, 100, '20120502'
UNION ALL SELECT 2, 2, 100, '20120505';

询问:

;WITH x AS 
(
  SELECT InvoiceID, ReceiptID, Amount, DateAdded, 
   rn = ROW_NUMBER() OVER (ORDER BY DateAdded)
  FROM
  (
    SELECT InvoiceID, ReceiptID = 0, Amount, DateAdded
    FROM dbo.Invoices -- where clause?
    UNION ALL 
    SELECT InvoiceID, ReceiptID, Amount, DateAdded
    FROM dbo.Receipts -- where clause?
  ) AS y
),
z AS
(
  SELECT xrn = x.rn, x.InvoiceID, x.ReceiptID, x.Amount, x.DateAdded, 
    PlusMinus = CASE WHEN x.ReceiptID > 0 THEN -x.Amount ELSE x.Amount END
    FROM x LEFT OUTER JOIN x AS x2
    ON x.rn = x2.rn + 1
)
SELECT InvoiceID, ReceiptID, Balance = (
  SELECT SUM(COALESCE(PlusMinus, Amount)) 
  FROM z AS z2 
  WHERE z2.xrn <= z.xrn
), Amount, DateAdded
FROM z
ORDER BY DateAdded;

清理:

DROP TABLE dbo.Invoices, dbo.Receipts;
于 2012-05-01T22:34:58.717 回答
-1

如果数据库是 oracle,您可以创建一个从 2 个表中选择数据的视图:

CREATE VIEW INVOICE_RECPT_VIEW as 
select a.InvoiceID, b.RecieptID, b.Amount, b.Date_Added 
from invoices a, receipts b 
where a.InvoiceID = b.InvoiceID 
order by Date_Added
于 2012-05-01T22:16:28.307 回答