query with dates

I want to return the last 12 months as header

so if  today's date is 12/01/17 it would do this

01/17 02/17 03/17 04/17 05/17 06/17 07/17 08/17 09/17 10/17 11/17 12/17 TOTAL

under each date I need the count of records from table where the purchasemonth = the month of the heading

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nakul VachhrajaniTechnical Architect, Capgemini IndiaCommented:
Without a table structure it is difficult to work out a query, but I have developed the following sample that demonstrates how one can use PIVOT to achieve a similar requirement.

USE tempdb;
DECLARE @myTable TABLE (RecordDate DATE,
                        DummyData VARCHAR(20) DEFAULT ('DummyForCount')

INSERT INTO @myTable (RecordDate)
VALUES ('20180506'),
       --Following should not be counted as they lie outside the date range

--Check Data
SELECT mt.RecordDate, mt.DummyData FROM @myTable AS mt ORDER BY mt.RecordDate

--Develop the Query
SELECT PivotedData.[0],
FROM (SELECT --mt.RecordDate,
             DATEDIFF(MONTH,RecordDate,GETDATE()) AS MonthOut
      FROM @myTable AS mt
      WHERE DATEDIFF(MONTH,RecordDate,GETDATE()) <= 12
     ) AS SourceData 
PIVOT (COUNT(SourceData.DummyData) 
       FOR MonthOut IN ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
      ) AS PivotedData

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vbnetcoderAuthor Commented:
That looks about right but i need to go back 12 months for the current date. How would i add that in?
Nakul VachhrajaniTechnical Architect, Capgemini IndiaCommented:
It is going back 12 months from current date. All operations are using GETDATE() which gives the current date.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

vbnetcoderAuthor Commented:
How would I not hardcode the dates on the insert?
Nakul VachhrajaniTechnical Architect, Capgemini IndiaCommented:
My query is just a sample to be used as reference/guidance. I am assuming that you already have a table with all the data available (hence the comment about sharing the underlying data structures and sample data in the question being useful).

The core work is in the final SELECT with the PIVOT. You will need to rewrite the query to work with your tables and your data.
Mark WillsTopic AdvisorCommented:
Lets say your Purchases table has Customer, Quantity, and [date] in it.... To guarantee the months we could use a CTE to calculate dates
Declare @end date = '20171201'
Declare @start date = dateadd(month,-12,@end)

;with CTE_Dates as
( select @start [date]
  union all
  select dateadd(month,1,[date])
  from CTE_Dates
  where [date]<=@end
) select * from
  ( select p.customer,p.quantity, c.[date] from CTE_Dates c left outer join purchases p on p.[date] >= c.[date] and p.[date] < dateadd(month,1,c.[date])) src
  ( sum(quantity) for [date] in ([20170101],[20170201],[20170301],[20170401],[20170501],[20170601],[20170701],[20170801],[20170901],[20171001],[20171101],[20171201])) pvt

Open in new window

However because we end up pivot we dont need the CTE because the pivot is going to do that for us
select * from
  ( select p.customer,p.quantity, convert(varchar(6),p.[date],112)+'01' [date] from purchases p ) src
  ( sum(quantity) for [date] in ([20170101],[20170201],[20170301],[20170401],[20170501],[20170601],[20170701],[20170801],[20170901],[20171001],[20171101],[20171201])) pvt

Open in new window

But then again, I dont know where PIVOT became part of the requirement.... As opposed to needing every month being covered off...

In which case, back to our CTE
Declare @end date = '20171201'
Declare @start date = dateadd(month,-12,@end)

;with CTE_Dates as
( select @start [date]
  union all
  select dateadd(month,1,[date])
  from CTE_Dates
  where [date]<=@end
) select j.customer,isnull(p.quantity,0) quantity, c.[date] 
  from CTE_Dates c 
  cross join (select distinct customer from purchases) j 
  left outer join purchases p on j.customer = p.customer and p.[date] >= c.[date] and p.[date] < dateadd(month,1,c.[date])
order by 1,3,2

Open in new window

Of course some refinements would be needed (e.g. checking for calendar year), but should be enough to get you started....
vbnetcoderAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.