Mid
Detailed answer
Dates & Aggregation
SQL & Databases
How do you get year-to-date sales per customer?
Short answer: Filter OrderDate from Jan 1 of current year, GROUP BY CustomerId, SUM(Amount). Or use a window with PARTITION BY CustomerId and a date filter.
Sample solution
T-SQL
DECLARE @Start DATE = DATEFROMPARTS(YEAR(GETDATE()), 1, 1); SELECT CustomerId, SUM(Amount) AS YtdSales FROM Orders WHERE OrderDate >= @Start AND OrderDate < DATEADD(DAY, 1, CAST(GETDATE() AS date)) GROUP BY CustomerId;
Half-open date ranges [start, end) avoid time-of-day bugs.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png