TSQL -> SQL 2012. Using Window Function for calculated column

We want to make general select from Invoices table, but add to it calculated column: income Balance until current record. Select is ordered by invoice date.

USE colombo
GO

-- CORRELATED SUBQUERY (2008 style)
SELECT a.DocNo, a.DocDate, a.CustomerID, a.CustomerName, a.DocTotal,
  (select SUM(b.DocTotal)
   from dbo.Invoice AS b
   where b.DocDate <= a.DocDate ) AS Balance
FROM dbo.Invoice AS a
ORDER BY a.DocDate
GO

-- WINDOW FUNCTION (2012 style)
SELECT iv.DocNo, iv.DocDate, iv.CustomerID, iv.CustomerName, iv.DocTotal,
  SUM(iv.DocTotal) OVER (ORDER BY iv.DocDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  AS Balance
FROM dbo.Invoice AS iv
ORDER BY iv.DocDate
GO

-- Pay attention to Execution plans of two queries !



The query returns results like these:
DocNoDocDateCustomerIDCustomerNameDocTotal Balance
231998-10-0417Bruce Davenport12501250
11999-01-141Angelina Alba23753625
191999-01-184Pestiana Oliviera1951.65576.6
21999-01-224Pestiana Oliviera1291.56868.1
31999-02-148Enrice Durance1020017068.1
201999-02-198Enrice Durance37517443.1
..................




sqlexamples.info