Question

PIVOT Table 12 Months Forcast

Asked by: smaguire

Hi,
I am using a PIVOT table to put my values in a 12 months forcast, the problem i am having is my months are static and I would like them to be dynamics meaning:
Currently we are in the month of Nov-2009, I would like to show 12 months forcast with first month is the current month, so instead of showing:
Jan, Feb, ... Dec. I want to see:
Nov, Dec, Jan(2010),....,Nov(2010).
My problem is the code i have is placing values for example in Jan-2009 thinking its Jan-2010 and so on
Please check my attachment picture for clearer idea.
Does anyone know how to modify the attached code to show the desired results?
Thanks

SELECT *
FROM(
  SELECT
    CASE MONTH(Invoice.[Date])
      WHEN 1 THEN 'January'
      WHEN 2 THEN 'February'
      WHEN 3 THEN 'March'
      WHEN 4 THEN 'April'
      WHEN 5 THEN 'May'
      WHEN 6 THEN 'June'
      WHEN 7 THEN 'July'
      WHEN 8 THEN 'August'
      WHEN 9 THEN 'September'
      WHEN 10 THEN 'October'
      WHEN 11 THEN 'November'
      WHEN 12 THEN 'December'
    END AS [Month],
    Invoice.InvoiceNo [InvoiceNo], 
    InvoiceLine.Amount [Amount],
    Project.Number [Number]
  FROM Invoice INNER JOIN InvoiceLine ON Invoice.InvoiceId = InvoiceLine.InvoiceId LEFT OUTER JOIN
	   Project ON Invoice.ProjectId =  Project.ProjectId
) InvoiceLine
PIVOT
(
  SUM(InvoiceLine.Amount)
  FOR [Month] IN (
    [January],[February],[March],[April],
    [May],[June],[July],[August],
    [September],[October],[November],[December]
  )
) AS PivotTable
ORDER BY [Number] DESC

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-05 at 08:41:01ID24875012
Tags

MS SQL Server 2008

Topics

SQL Server 2008

,

SQL Server 2005

Participating Experts
2
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. pivot table?
    Is there any implementation of a simple pivot table in javascipt? After getting data from oracle database, I want user to be able to manipulate the data in any way they want within the browser. Thanks. Sean
  2. Views: CrossTab, Pivotting
    Hello Does anyone know how to pivot a range of multiple values(wwyy) in ONE column, so that each month has it's OWN column .. e.g. from >> 1 0104 2 0104 3 0204 4 0304 5 0404 to >> Jan Feb Mar Apr 1 (1) 2 (1) 3 (1) 4 (1) 5...
  3. Pivot Table month grouping - Not getting the dialog to select…
    Im attempting to create a pivot table in Excel 2007 of CRM call history based on data imported from SQL Server. The table will reflect the number of product discussion by month. Once imported Ive created the pivot table and want the format to look as follows: Jan Feb M...
  4. Pivot Unpivot
    How do i pivot/unpivot the follwoing result month column1 column2 ----- ------- ------- jan 1 33 feb 3 33 mar 33 22 to columns jan feb mar column1 1 3 33 colum2 33 33 22

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: aneeshattingalPosted on 2009-11-05 at 09:11:40ID: 25751640

SELECT *
FROM(
  SELECT
    CASE MONTH(Invoice.[Date])
      WHEN 1 THEN 'January'
      WHEN 2 THEN 'February'
      WHEN 3 THEN 'March'
      WHEN 4 THEN 'April'
      WHEN 5 THEN 'May'
      WHEN 6 THEN 'June'
      WHEN 7 THEN 'July'
      WHEN 8 THEN 'August'
      WHEN 9 THEN 'September'
      WHEN 10 THEN 'October'
      WHEN 11 THEN 'November'
      WHEN 12 THEN 'December'
    END AS [Month],
    Invoice.InvoiceNo [InvoiceNo],
    InvoiceLine.Amount [Amount],
    Project.Number [Number]
  FROM Invoice
  INNER JOIN InvoiceLine ON Invoice.InvoiceId = InvoiceLine.InvoiceId
  LEFT OUTER JOIN Project ON Invoice.ProjectId =  Project.ProjectId
  WHERE Invoice.[Date] >=DATEADD(month, DATEDIFF(month, '', getdate() ) , '')
) InvoiceLine
PIVOT
(
  SUM(InvoiceLine.Amount)
  FOR [Month] IN (
    [January],[February],[March],[April],
    [May],[June],[July],[August],
    [September],[October],[November],[December]
  )
) AS PivotTable
ORDER BY [Number] DESC


 

by: mwvisa1Posted on 2009-11-05 at 09:30:00ID: 25751811

If you want to change the display to include the year, you may need to go to dynamic SQL.

FYI, you can use DATENAME() to simplify getting the month name:
datename( month, Invoice.[Date] )

You can then concatenate the year to that, but again to get this in the pivot you will have to use dynamic SQL approach.  Please read here:

Dynamic Pivot Procedure for SQL Server - http:A_653.html

 

by: smaguirePosted on 2009-11-05 at 09:53:26ID: 25752022

Thank you guys for your replies,

aneeshattingal: Your code doesn't work, I've attached a picture of the result of your code

mwvisa1:  I will go over the link and let you know

Thanks

 

by: mwvisa1Posted on 2009-11-05 at 11:24:07ID: 25752938

Okay.  An alternative would be to code as dynamic rolling period, so you would end up with :

CurrentMonth, 1Month, 2Months, 3Months, etc.

Pivot Rolling Periods Without Using Dynamic T-SQL - http:A_654.html

You would basically, use DATEDIFF() to calculate the difference in months from current date then use [0] - [12] in your query.  

Since this is a forecast, you may be looking to get the prior year's data and fill it in but with current month first so that on paper it looks like projected values you can then change.  If that is the case, the NULLs may have been what looked wrong in Aneesh's aside from the column names.  With that being said, please try this :


SELECT [InvoiceNo], [Number]
    , [0] AS CurrentMonth
    , [11] AS NextMonth
    , [10] AS 2MonthsFromNow
    , [9] AS 3MonthsFromNow
    , [8] AS 4MonthsFromNow
    , [7] AS 5MonthsFromNow
    , [6] AS 6MonthsFromNow
    , [5] AS 7MonthsFromNow
    , [4] AS 8MonthsFromNow
    , [3] AS 9MonthsFromNow
    , [2] AS 10MonthsFromNow
    , [1] AS 11MonthsFromNow
    , [12] AS CurrentMonthNextYear
FROM
(
  SELECT DATEDIFF(MONTH, Invoice.[Date], GETDATE()) [Month],
     Invoice.InvoiceNo [InvoiceNo],
     InvoiceLine.Amount [Amount],
     Project.Number [Number]
  FROM Invoice
  INNER JOIN InvoiceLine ON Invoice.InvoiceId = InvoiceLine.InvoiceId
  LEFT OUTER JOIN Project ON Invoice.ProjectId = Project.ProjectId
) AS InvoiceLine
PIVOT
(
  SUM(InvoiceLine.Amount)
  FOR [Month] IN (
     [0],[1],[2],[3],[4]
     [5],[6],[7],[8],
     [9],[10],[11],[12]
  )
) AS PivotTable
ORDER BY [Number] DESC



If you want it as Aneesh had, then add back the date criteria and change this portion of code :

DATEDIFF(MONTH, Invoice.[Date], GETDATE())

To :

DATEDIFF(MONTH, GETDATE(), Invoice.[Date])

Then the columns become this :
, [0] AS CurrentMonth
    , [1] AS NextMonth
    , [2] AS 2MonthsFromNow

...
,[12] AS CurrentMonthNextYear


Now you have the best of both worlds where you don't have to update the query each month or deal with dynamic SQL while having some indication in the column name what month you are dealing with.  If the Nov-2009, etc. identification is a must have then as I said the Article by Mark is a good starting place.


Regards,

Kevin

 

by: smaguirePosted on 2009-11-05 at 11:51:57ID: 25753214

Thanks Kevin for your support,

I am getting an error with your code, please see the attachment

I am roaming around the same idea as yours, please see the attached code (pseudo code)

strSEL = N'SELECT *
FROM(
  SELECT
    CASE MONTH(Invoice.[Date]) --Date subtraction gives you 0 to 11
      WHEN 1 THEN ' + MonthString(DateAdd(m,0,Date.Now )) + '-' + YearString(DateAdd(m,0,Date.Now)) + '
      WHEN 2 THEN ' + MonthString(DateAdd(m,1,Date.Now )) + '
      WHEN 3 THEN MonthString(DateAdd(m,2,Date.Now ))
      WHEN 4 THEN MonthString(DateAdd(m,3,Date.Now ))
      WHEN 5 THEN MonthString(DateAdd(m,4,Date.Now ))
      WHEN 6 THEN MonthString(DateAdd(m,5,Date.Now ))
      WHEN 7 THEN 'July'
      WHEN 8 THEN 'August'
      WHEN 9 THEN 'September'
      WHEN 10 THEN 'October'
      WHEN 11 THEN 'November'
      WHEN 12 THEN 'December'
    END AS [Month],
    Invoice.InvoiceNo [InvoiceNo], 
    InvoiceLine.Amount [Amount],
    Project.Number [Number]
  FROM Invoice INNER JOIN InvoiceLine ON Invoice.InvoiceId = InvoiceLine.InvoiceId LEFT OUTER JOIN
	   Project ON Invoice.ProjectId =  Project.ProjectId
) InvoiceLine
PIVOT
(
  SUM(InvoiceLine.Amount)
  FOR [Month] IN (
    MonthString(DateAdd(m,0,Date.Now )),[February],[March],[April],
    [May],[June],[July],[August],
    [September],[October],[November],[December]
  )
) AS PivotTable
ORDER BY [Number] DESC

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

Select allOpen in new window

 

by: mwvisa1Posted on 2009-11-05 at 12:05:09ID: 25753351

Sorry, my mistake.  Typing too quickly.  You have to put brackets or something around the name since it starts with number.

I will look at your attempt.

SELECT [InvoiceNo], [Number]
    , [0] AS CurrentMonth
    , [11] AS NextMonth
    , [10] AS 2MonthsFromNow
    , [9] AS 3MonthsFromNow
    , [8] AS 4MonthsFromNow
    , [7] AS 5MonthsFromNow
    , [6] AS 6MonthsFromNow
    , [5] AS 7MonthsFromNow
    , [4] AS 8MonthsFromNow
    , [3] AS 9MonthsFromNow
    , [2] AS 10MonthsFromNow
    , [1] AS 11MonthsFromNow
    , [12] AS CurrentMonthNextYear
FROM
(
  SELECT DATEDIFF(MONTH, Invoice.[Date], GETDATE()) [Month],
     Invoice.InvoiceNo [InvoiceNo],
     InvoiceLine.Amount [Amount],
     Project.Number [Number]
  FROM Invoice
  INNER JOIN InvoiceLine ON Invoice.InvoiceId = InvoiceLine.InvoiceId
  LEFT OUTER JOIN Project ON Invoice.ProjectId = Project.ProjectId
) AS InvoiceLine
PIVOT
(
  SUM(InvoiceLine.Amount)
  FOR [Month] IN (
     [0],[1],[2],[3],[4]
     [5],[6],[7],[8],
     [9],[10],[11],[12]
  )
) AS PivotTable
ORDER BY [Number] DESC

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

Select allOpen in new window

 

by: smaguirePosted on 2009-11-05 at 12:49:38ID: 25753857

here is my improved code,  the values under the pivot:

[0],[1],[2],[3],[4]
    [5],[6],[7],[8],
    [9],[10],[11],[12]
are giving me some problems, what should go there instead?

Thanks

SELECT *
FROM(
  SELECT
    CASE DATEDIFF(m,Invoice.[Date],GETDATE())  --Date subtraction gives you 0 to 11
      WHEN 0 THEN DateAdd(MONTH, 0, GETDATE()) 
      WHEN 1 THEN DateAdd(MONTH, 1, GETDATE())
      WHEN 2 THEN DateAdd(MONTH, 2, GETDATE())
      WHEN 3 THEN DateAdd(MONTH, 3, GETDATE())
      WHEN 4 THEN DateAdd(MONTH, 4, GETDATE())
      WHEN 5 THEN DateAdd(MONTH, 5, GETDATE())
      WHEN 6 THEN DateAdd(MONTH, 6, GETDATE())
      WHEN 7 THEN DateAdd(MONTH, 7, GETDATE())
      WHEN 8 THEN DateAdd(MONTH, 8, GETDATE())
      WHEN 9 THEN DateAdd(MONTH, 9, GETDATE())
      WHEN 10 THEN DateAdd(MONTH, 10, GETDATE())
      WHEN 11 THEN DateAdd(MONTH, 11, GETDATE())
    END AS [Month],
    Invoice.InvoiceNo [InvoiceNo], 
    InvoiceLine.Amount [Amount],
    Project.Number [Number]
  FROM Invoice INNER JOIN InvoiceLine ON Invoice.InvoiceId = InvoiceLine.InvoiceId LEFT OUTER JOIN
	   Project ON Invoice.ProjectId =  Project.ProjectId
) InvoiceLine
PIVOT
(
  SUM(InvoiceLine.Amount)
  FOR [Month] IN (
    DateAdd(MONTH, 0, GETDATE()),[2],[3],[4],
    [5],[6],[7],[8],
    [9],[10],[11],[12]
  )
) AS PivotTable
ORDER BY [Number] DESC

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

Select allOpen in new window

 

by: mwvisa1Posted on 2009-11-05 at 12:54:00ID: 25753891

[0],[1],[2],[3],[4]
    [5],[6],[7],[8],
    [9],[10],[11],[12]

The above values go along with DATEDIFF().

It looks like a type-o as there is a missing comma (,).

[0],[1],[2],[3],[4],
    [5],[6],[7],[8],
    [9],[10],[11],[12]

If you change the [Month] column to other data, then the IN statement must have valid values that will in turn become the columns.

 

by: smaguirePosted on 2009-11-05 at 12:59:40ID: 25753958

Almost there!

Does the code make sense? I am getting one more error, I am attaching it in the picture

Thanks for your support

 

by: mwvisa1Posted on 2009-11-05 at 13:48:09ID: 25754419

That is because you are taking the DATEDIFF() which returns values of 0 - 12 where 0 = this month and 12 = Nov. 2008 and you are doing DATEADD() to end up with 2009-11-05 (today) - 2010-10-05 (2010-11-05 if 12 was included).  These are also DATETIME values and will not compare to [0], [1], etc.

You must make choice between my approach of rolling periods OR will have to go full blow dynamic SQL ; in between does not work unfortunately due to the hard coded values requirement of PIVOT.  Another alternative is to get your data "as-is" into a view and then pull this data in an MS Access database or Excel via MS Query / ODBC / Linked Table and then use the Pivot Table (Crosstab Query) features available there to pivot the data for you.

Regards,

Kevin

 

by: smaguirePosted on 2009-11-05 at 13:51:52ID: 25754453

Okay fair enough, I will play with it later.

You will get the points.

Thanks

 

by: mwvisa1Posted on 2009-11-05 at 14:06:18ID: 25754575

Sorry to disappoint you, but pivoting can be a challenge.  :)
As I said, Excel and Access since the data is already represented, can use PivotTable or Transform ... Pivot construct (Access) and generate the columns names using the data.  For SQL Server, you have to do this manually using case statements or Pivot keyword and hard coded column names, using Pivot with with rolling periods trick I showed or different variations of dynamic SQL to get the column names and then construct a Pivot statement which executes with static column names as needed but you don't have to type. :)


Mark has done all the heavy lifting for you in the Article by providing as a bonus a working stored procedure that can run against a view and pivot the data for you, so have a serious look if the column names with date is a requirement you can't budge on.


Thanks for the accepted solution and points.

Just glad I could help.

Best regards and happy coding,

Kevin

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...