SQL QUERY - Filter date from the beginning

Viewed 92

How to write SQL query that will sum the amount from the previous days/years. Like from the start.

Scenario I want to compute accumulated sales of the store from the day it was opened.

Example

SELECT SUM(AMOUNT) 
FROM TransactionTable 
WHERE TransactionDate = ???

The plan that I have is to query on this table and get the oldest transaction date record, then I will use that in the WHERE condition. Do you think that it is the best solution?

3 Answers

You can try below using having min(transaction) which will give you the date when transaction first started

select sum (amt) from
(
  SELECT SUM(AMOUNT) as amt from TransactionTable 
  group by TransactionDate 
  having TransactionDate between min(TransactionDate) and getdate()
)A

To compute accumulated sales of the store from the day it started you can use SUM with OVER clause

SELECT TransactionDate, SUM(AMOUNT) OVER (ORDER BY TransactionDate) AS AccumulatedSales
FROM TransactionTable 

use group by TransactionDate

SELECT convert(date,TransactionDate), SUM(AMOUNT) from TransactionTable 
group by  convert(date,TransactionDate) 
Related