Solved

SQL Pivot Query

Posted on 2011-02-23
9
472 Views
Last Modified: 2012-05-11
Hi Experts,I am working on a forecasting application to get rid of an Excel spreadsheet and I've come across some trouble. After reading around it looks as if I need to use the Pivot functionality. I have attached a screenshot showing a simplistic version of the spreadsheet and how data is organised and a few results from queries in the database that I am now working on. Looking at that I need help with what the query should be to get the result set as the spreadsheet.  EXCEL SQL VIEW
0
Comment
Question by:takwirirar
  • 6
  • 3
9 Comments
 
LVL 15

Accepted Solution

by:
derekkromm earned 500 total points
Comment Utility
Here is an example of how to use a PIVOT query, you should be able to substitute your actual table/column names in easily. The problem with using PIVOT is that you have to specify each pivoted column (i.e. you'll have to enumerate each week). To get around that, you'd have to use dynamic SQL to generate the list of pivots on the fly.

declare @t table (
	p int,
	sku varchar(100),
	d varchar(100),
	customer varchar(100),
	forecast int,
	w int
)

insert into @t
select 111, 'SINGLE', 'LINGETTESx61', 'BES001', 10, 1
union select 111, 'SINGLE', 'LINGETTESx61', 'BES001', 20, 2
union select 111, 'SINGLE', 'LINGETTESx61', 'BES001', 21, 3
union select 111, 'SINGLE', 'LINGETTESx61', 'BES001', 33, 4
union select 113, 'SINGLE', 'NIBLETTESx61', 'BES001', 10, 1

select
	p, sku, d, customer, [1], [2], [3], [4]
from
	(select p, sku, d, customer, forecast, w from @t) as SourceTable
pivot (
	sum(forecast)
	for w in ([1], [2], [3], [4])
) as pvt

Open in new window

0
 
LVL 1

Author Comment

by:takwirirar
Comment Utility
Im getting the error

Msg 170, Level 15, State 1, Line 21
Line 21: Incorrect syntax near 'pivot'.
0
 
LVL 15

Expert Comment

by:derekkromm
Comment Utility
can you post the whole query that is giving you the error? when i copy/paste my code i don't get any errors
0
 
LVL 1

Author Comment

by:takwirirar
Comment Utility
Hi Derek, this is the code I ended up with, you are correct a copy and pasted yours and didnt get any errors. Im just struggling to interpret it for my data. The error now is

Msg 107, Level 15, State 1, Line 6
The column prefix 'vf' does not match with a table name or alias name used in the query.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'w'.

select
	[Product Code],[SKU],[Description],Customer,Forecast,[Week ID], [1], [2], [3], [4]
from
	(select pr.[Product Code],pr.[SKU],pr.[Description],vf.Customer,vf.forecast,wk.[Week ID] from dbo.[Products] pr LEFT JOIN dbo.[Volume Forecast] AS vf ON pr.[Product Code] = vf.[Product Code] LEFT JOIN dbo.[Weeks] AS wk ON vf.[Week ID] = wk.[Week ID]) as SourceTable
pivot (
	sum(vf.forecast)
	for w in ([1], [2], [3], [4])
) as pvt

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 1

Author Comment

by:takwirirar
Comment Utility
Hi Derek, I checked the code again and changed it to the below. Please find the results I get now. New Results
select
	[Product Code],[SKU],[Description],Customer,[Week ID], [1], [2], [3], [4]
from
	(select pr.[Product Code],pr.[SKU],pr.[Description],vf.Customer,vf.forecast,wk.[Week ID] from dbo.[Products] pr LEFT JOIN dbo.[Volume Forecast] AS vf ON pr.[Product Code] = vf.[Product Code] LEFT JOIN dbo.[Weeks] AS wk ON vf.[Week ID] = wk.[Week ID]) as SourceTable
pivot (
	sum(forecast)
	for forecast in ([1], [2], [3], [4])
) as pvt

Open in new window

0
 
LVL 1

Author Comment

by:takwirirar
Comment Utility
Hi Derek, I have looked at you example again and saw my mistake please find new code below. I am now getting error;


Msg 207, Level 16, State 1, Line 2
Invalid column name 'Week ID'.

select
	[Product Code],[SKU],[Description],Customer,[Week ID], [1], [2], [3], [4]
from
	(select pr.[Product Code],pr.[SKU],pr.[Description],vf.Customer,vf.forecast,wk.[Week ID] from dbo.[Products] pr LEFT JOIN dbo.[Volume Forecast] AS vf ON pr.[Product Code] = vf.[Product Code] LEFT JOIN dbo.[Weeks] AS wk ON vf.[Week ID] = wk.[Week ID]) as SourceTable
pivot (
	sum(forecast)
	for [Week ID] in ([1], [2], [3], [4])
) as pvt

Open in new window

0
 
LVL 1

Author Comment

by:takwirirar
Comment Utility
Hi Derek, I am a bit embarrased! I've looked at your code again and my code below now works. I just need to add the extra complexity now that I have the basics covered. If I find any trouble I will open a related question. Thank you for your help and allowing me to figure this myself.
select
	[Product Code],[SKU],[Description],Customer, [1], [2], [3], [4]
from
	(select pr.[Product Code],pr.[SKU],pr.[Description],vf.Customer,vf.forecast,wk.[Week ID] from dbo.[Products] pr LEFT JOIN dbo.[Volume Forecast] AS vf ON pr.[Product Code] = vf.[Product Code] LEFT JOIN dbo.[Weeks] AS wk ON vf.[Week ID] = wk.[Week ID]) as SourceTable
pivot (
	sum(forecast)
	for [Week ID] in ([1], [2], [3], [4])
) as pvt

Open in new window

0
 
LVL 1

Author Closing Comment

by:takwirirar
Comment Utility
Thank you so much Derek. I will add the extra complexity and if I face issues will open a related question.
0
 
LVL 15

Expert Comment

by:derekkromm
Comment Utility
No problem
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Join & Write a Comment

Many companies are looking to get out of the datacenter business and to services like Microsoft Azure to provide Infrastructure as a Service (IaaS) solutions for legacy client server workloads, rather than continuing to make capital investments in h…
Never store passwords in plain text or just their hash: it seems a no-brainier, but there are still plenty of people doing that. I present the why and how on this subject, offering my own real life solution that you can implement right away, bringin…
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now