Skip to content

Instantly share code, notes, and snippets.

@tobiascoetzee
Created June 2, 2018 01:02
Show Gist options
  • Save tobiascoetzee/6453799f2339e94703543685b3523135 to your computer and use it in GitHub Desktop.
Save tobiascoetzee/6453799f2339e94703543685b3523135 to your computer and use it in GitHub Desktop.
SQL query that returns a list of all the products sold with a running total for each product and each day plus a total for each day and product using Windows over function
SET NOCOUNT ON;
SELECT
ProductID
,ModifiedDate
,UnitPrice
,SUM(UnitPrice) OVER (
PARTITION BY ModifiedDate
ORDER BY ProductID, ModifiedDate, SalesOrderID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) ASModifiedDateBalance
,SUM(UnitPrice) OVER (
PARTITION BY ProductID
ORDER BY ProductID, ModifiedDate, SalesOrderID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) ASProductIdBalance
,SUM(UnitPrice) OVER (
PARTITION BY ModifiedDate, ProductID) AS ModifiedDateTotal
,SUM(UnitPrice) OVER (
PARTITION BY ProductID) AS ProductIdTotal
FROM
Sales.SalesOrderDetail
ORDER BY ProductID, ModifiedDate, SalesOrderID;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment