sql >> Database teknologi >  >> RDS >> Sqlserver

Vælg løbende saldo fra tabellen kredit debet kolonner

Du skal selv deltage i bordet.

CREATE TABLE Test
(
  TransDate DATE,
  Credit INT,
  Debit INT,
);
INSERT INTO Test VALUES
('2014-01-01',   5000,      NULL),  
('2014-01-07',   NULL,      2000),   
('2014-01-11',   5000,      NULL),   
('2014-02-03',   6000,      NULL),    
('2014-02-06',   NULL,      4000),    
('2014-02-11',   3000,      NULL),   
('2014-02-21',   NULL,      1000),     
('2014-02-28',   2000,      NULL),     
('2014-03-01',   5000,      NULL) 

WITH CTE AS
(
SELECT t2.TransDate, 
       t2.Credit, 
       t2.Debit, 
       SUM(COALESCE(t1.credit, 0) - COALESCE(t1.debit, 0)) AS Balance
FROM Test t1 
INNER JOIN Test t2
    ON t1.TransDate <= t2.TransDate
WHERE t1.DataSource IN (3,4)  
GROUP BY t2.TransDate, t2.Credit, t2.Debit
)
SELECT * 
FROM CTE
WHERE (TransDate >= '2014/01/11' AND TransDate <= '2014/02/28' ) 

OUTPUT

TransDate   Credit  Debit   Balance
2014-01-11  5000    (null)  8000
2014-02-03  6000    (null)  14000
2014-02-06  (null)  4000    10000
2014-02-11  3000    (null)  13000
2014-02-21  (null)  1000    12000
2014-02-28  2000    (null)  14000

SQL FIDDLE



  1. Jeg kan ikke starte MySQL-serveren fra kommandolinjen i Windows

  2. ORA-22813:operandværdi overskrider systemgrænser

  3. Postgresql gem install pg 0.18.4 passerer, bundle installation mislykkes

  4. MySQL:Vælg kun e-mails fra én tabel, hvis ikke i en anden tabel?