Solved

SQL Pivot Query

Posted on 2011-02-23
9
498 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
ID: 34960737
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
ID: 34961297
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
ID: 34965394
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 1

Author Comment

by:takwirirar
ID: 34968758
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
 
LVL 1

Author Comment

by:takwirirar
ID: 34968793
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
ID: 34968853
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
ID: 34968867
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
ID: 34968873
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
ID: 34969633
No problem
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

CCModeler offers a way to enter basic information like entities, attributes and relationships and export them as yEd or erviz diagram. It also can import existing Access or SQL Server tables with relationships.
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
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…

831 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