• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 68
  • Last Modified:

count number of orders in 6 month intervals

I am trying to create a query\procedure that will show the total number of orders from a selected customer in 6 month intervals. For 6, 12, 18 and 24 months. Please show a step by step.

example if abc company order 6 times from Jan to Jun and 4 times from Jul-Dec then i want the report to show

company    6_Months    12_Months
acbc                   6                  10 <----- Rolling sum

I am using microsoft sql server 14
1 Solution
Kyle AbrahamsSenior .Net DeveloperCommented:
declare @date = DATEADD(d,0,DATEDIFF(d,0,GETDATE()))   -- today at midnight)

select company, 
-- if order is >= 6 months prior to today, add 1, else don't add anything end
sum (case when order_date >= dateadd(m, -6, @date) then 1 else 0 end) 6_Months,
sum (case when order_date >= dateadd(m, -12, @date) then 1 else 0 end) 12_Months
where company = @company
group by company

Open in new window

cskehanAuthor Commented:
Had to do a little tweaking to code, but you got me in the right directions. Thanks!!
Olaf DoschkeSoftware DeveloperCommented:
You might also look into my solution of a similar problem at https://www.experts-exchange.com/questions/28963238/SQL-sum-months-quarter-YTD.html#a41756192

Bye, Olaf
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now