SQL How to effectively use dynamic sql query when output COLUMN order is important - sql

My question is really how to ensure that the ORDER of the OUTPUT is maintained when using dynamic query to get data out. I have a couple of dynamic queries that I am utilizing and I notice that when I run the same query on different machines, I get output in different orders. Currently, I store the data outputted into a temp table which assume the order of the output to be the same as that on my local machine but on production, it is all switched up. How do I get more control of this so that every time the query is run, the order of the output is maintained?
When I go to use an Order BY in my dynamic query I get the error
Msg 1033, Level 15, State 1, Line 18
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
DECLARE #colsUnpivot AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#colsPivot as NVARCHAR(MAX)
IF EXISTS
(
SELECT *
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(N'tempdb..#ibutes')
)
BEGIN
DROP TABLE #ibutes
END
Create table #ibutes
(
ProductID uniqueIdentifier,
PAID uniqueidentifier,
Label nvarchar(50),
Val nvarchar(3072),
unit nvarchar(50)
)
;With Number
As
(
Select 1 as rownum union all Select 2 union all Select 3 union all Select 4 union all Select 5 union all Select 6 union all Select 7 union all Select 8 union all Select 9 union all Select 10 union all Select 11 union all Select 12 union all Select 13 union all Select 14 union all Select 15 union all Select 16 union all Select 17 union all Select 18 union all Select 19 union all Select 20 union all Select 21
),
ProductDetail
as
(
select P.ProdID, N.rownum from IDWProduct P cross join Number N
)
Insert into #ibutes
Select ProdID , PAVibuteID, COALESCE(PANAme,''), COALESCE(PAVValue,''), COALESCE(unitLabel,'')
from ProductDetail P
Left join
(select Pr.*, PAName, row_number() over (partition by PAVProductID order by PAVID) as Rn from IDWProductibuteValues Pr
inner join IDWibutes on PAID = PAVibuteID Where PAIscustom = 0 AND PAIsManufacturerSpecific =0 AND PANAME NOT IN
('Brand Name', 'Standard', 'Application', 'Sub Brand', 'Type', 'Special Features'))
Pr ON rownum = Pr.Rn And PAVProductID = ProdID
left join IDWUnitofMeasures on Pr.PAVunit = unitID
--Select * from #ibutes
select #colsUnpivot = stuff((select ','+quotename(C.name)
from tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#ibutes') AND C.name Not in ('ProductID')
for xml path('')), 1, 1, '')
--select #colsUnpivot
select #colsPivot = STUFF((SELECT ',' + quotename(c.name + cast(t.rn as varchar(10)))
from
(
select row_number() over(partition by ProductID order by ProductID) rn from #ibutes
) t
cross apply
tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#ibutes') AND C.name Not in ('ProductID')
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--select #colsPivot
set #query = 'select *
from
(
select ProductID,
col + cast(rn as varchar(10)) new_col,
val
from
(
select
Cast (PAID as NVarchar(3072)) PAID
,Cast (ProductID as NVarchar(3072)) ProductID
,Cast (Label as NVarchar(3072)) Label
,Cast (Val as NVarchar(3072)) Val
,Cast (unit as NVarchar(3072)) unit
,row_number() over(partition by ProductID order by ProductID) rn
from #ibutes
) x
unpivot
(
val
for col in ('+ #colsunpivot +')
) u
) x1
pivot
(
max(val)
for new_col in
('+ #colspivot +')
) p'
exec(#query)
The results of running the query
ON MY LOCAL/DEV MACHINE
========================
select *
from
(
select ProductID,
col + cast(rn as varchar(10)) new_col,
val
from
(
select
Cast (PAID as NVarchar(3072)) PAID
,Cast (ProductID as NVarchar(3072)) ProductID
,Cast (Label as NVarchar(3072)) Label
,Cast (Val as NVarchar(3072)) Val
,Cast (unit as NVarchar(3072)) unit
,row_number() over(partition by ProductID order by ProductID) rn
from #ibutes
) x
unpivot
(
val
for col in ([Label],[unit],[Val],[PAID])
) u
) x1
pivot
(
max(val)
for new_col in
([Label1],[unit1],[Val1],[PAID1],[Label2],[unit2],[Val2],[PAID2],[Label3],[unit3],[Val3],[PAID3],[Label4],[unit4],[Val4],[PAID4],[Label5],[unit5],[Val5],[PAID5],[Label6],[unit6],[Val6],[PAID6],[Label7],[unit7],[Val7],[PAID7],[Label8],[unit8],[Val8],[PAID8],[Label9],[unit9],[Val9],[PAID9],[Label10],[unit10],[Val10],[PAID10],[Label11],[unit11],[Val11],[PAID11],[Label12],[unit12],[Val12],[PAID12],[Label13],[unit13],[Val13],[PAID13],[Label14],[unit14],[Val14],[PAID14],[Label15],[unit15],[Val15],[PAID15],[Label16],[unit16],[Val16],[PAID16],[Label17],[unit17],[Val17],[PAID17],[Label18],[unit18],[Val18],[PAID18],[Label19],[unit19],[Val19],[PAID19],[Label20],[unit20],[Val20],[PAID20],[Label21],[unit21],[Val21],[PAID21])
) p
ON PRODUCTION MACHINE HOWEVER IT IS DIFFERENT. PLEASE NOTICE THE CHANGE IN ORDER OF THE
COLUMNS
select *
from
(
select ProductID,
col + cast(rn as varchar(10)) new_col,
val
from
(
select
Cast (PAID as NVarchar(3072)) PAID
,Cast (ProductID as NVarchar(3072)) ProductID
,Cast (Label as NVarchar(3072)) Label
,Cast (Val as NVarchar(3072)) Val
,Cast (Unit as NVarchar(3072)) Unit
,row_number() over(partition by ProductID order by ProductID) rn
from #ibutes
) x
unpivot
(
val
for col in ([PAID],[Label],[Val],[Unit])
) u
) x1
pivot
(
max(val)
for new_col in
([PAID1],[Label1],[Val1],[Unit1],[PAID2],[Label2],[Val2],[Unit2],[PAID3],[Label3],[Val3],[Unit3],[PAID4],[Label4],[Val4],[Unit4],[PAID5],[Label5],[Val5],[Unit5],[PAID6],[Label6],[Val6],[Unit6],[PAID7],[Label7],[Val7],[Unit7],[PAID8],[Label8],[Val8],[Unit8],[PAID9],[Label9],[Val9],[Unit9],[PAID10],[Label10],[Val10],[Unit10],[PAID11],[Label11],[Val11],[Unit11],[PAID12],[Label12],[Val12],[Unit12],[PAID13],[Label13],[Val13],[Unit13],[PAID14],[Label14],[Val14],[Unit14],[PAID15],[Label15],[Val15],[Unit15],[PAID16],[Label16],[Val16],[Unit16],[PAID17],[Label17],[Val17],[Unit17],[PAID18],[Label18],[Val18],[Unit18],[PAID19],[Label19],[Val19],[Unit19],[PAID20],[Label20],[Val20],[Unit20],[PAID21],[Label21],[Val21],[Unit21])
) p
Please note the difference btw local machine where the order seems alphabetical
[Label1],[unit1],[Val1],[PAID1],[Label2],[unit2].
. . .
while on Production machine, it is not
[PAID1],[Label1],[Val1],[Unit1],[PAID2],[Label2],[Val2],[Unit2], .. . . .

I think there is one only obvious answer. Use the order by clause in the dynamic query.

Simply, all queries whether dynamic or not are not guaranteed to come out the same on different machines!
If the order of the results is important to you, use ORDER BY
For example:
SELECT *
FROM TBL
ORDER BY FIRSTNAME

If you want order then use an order by.
In absence of an order by there is no guaranteed order.
If there is a tie then no guarantee the sort will repeat on the tie.
Use enough columns there is no tie.
It appears you are referring to order of the columns not rows.
If you select * you will the the columns in the order they are defined in the table.
If you need to control the order of the columns then don't use *.
select table1.col4, table1.col2
from table1

May be you can try this
'select *
from
(
select ProductID,
col + cast(rn as varchar(10)) new_col,
val
from
(
select top 100 percent
Cast (PAID as NVarchar(3072)) PAID
,Cast (ProductID as NVarchar(3072)) ProductID
,Cast (Label as NVarchar(3072)) Label
,Cast (Val as NVarchar(3072)) Val
,Cast (unit as NVarchar(3072)) unit
,row_number() over(partition by ProductID order by ProductID) rn
from #ibutes
order by row_number() over(partition by ProductID order by ProductID) asc
) x
unpivot
(
val
for col in ('+ #colsunpivot +')
) u
) x1
pivot
(
max(val)
for new_col in
('+ #colspivot +')
) p'

Now that we know where you're adding the ORDER BY, the answer is clearer.
You're trying to order the query whose results are inserted into #colsPivot and that's the problem.
ORDER BY is mainly used for ordering the final results and thus should be on the final query (the dynamic one).
The exception to this is if it is used as part of a "limiting" query (eg. TOP 10).
Try adding the ORDER BY to the dynamic query and let us know if it worked.

why not change the following:
set #query = 'select *
from
to something like
set #query = 'select *
into #x
from
you'll need to explicitly create #x before the dynamic sql i.e
create table #x
(
blah int,
blah char(8)
)
then after the exec statement have a further query
select *
from #x
order by whatever

Can you try the following?
Add the order by below to the first query
select #colsUnpivot = stuff((select ','+quotename(C.name)
from tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#ibutes') AND C.name Not in ('ProductID')
ORDER BY c.column_id --Add this
for xml path('')), 1, 1, '')
change the order by below of the second query
select #colsPivot = STUFF((SELECT ',' + quotename(c.name + cast(t.rn as varchar(10)))
from
(
select row_number() over(partition by ProductID order by ProductID) rn from #ibutes
) t
cross apply
tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#ibutes') AND C.name Not in ('ProductID')
group by c.name, t.rn
ORDER BY c.column_id --Change this
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
Hope that helps...

Related

Pivot multiple rows in initial table

I have a table which i would like to pivot to show how many categories a person is affiliated with...
I would like to pivot this to show:
There are a lot more members and categories but the theory i believe should be the same.
I have attempted this however it only shows the first line for each.
Thanks in advance
Will
#Will, this is the logic you need. Basically a pivot function on the column of interest.
DECLARE #tbl TABLE (RegNo varchar(20), Category varchar(20), Number int)
INSERT INTO #tbl
SELECT 'R1050162', 'Gym', 1 UNION ALL
SELECT 'R1050162', 'Personal Trainer', 1 UNION ALL
SELECT 'R0093126', 'Group Exercise', 1 UNION ALL
SELECT 'R0143614', 'Yoga Teacher', 1
SELECT *
FROM
#tbl
PIVOT
(
SUM(Number)
FOR Category IN ([Gym], [Personal Trainer], [Group Exercise], [Yoga Teacher]
)
) AS PivotTable;
Output is below:
You need to use just sum the Number field in PIVOT function and for numerous categories get a category list:
DECLARE #categories AS NVARCHAR(MAX),
#your_query AS NVARCHAR(MAX);
select #categories = STUFF((SELECT distinct ',' + QUOTENAME(Category)
FROM your_table
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT RegNo, ' + #categories + ' from
(
SELECT RegNo, Category, Number FROM your_table) tab
PIVOT
(
SUM(Number)
FOR Category IN (' + #categories + ')
) p iv
ORDER BY piv.RegNo'
execute(#your_query)

converting rows to columns dynamicaly based on conditions

In the below image I have current data and expected data based on the first three columns the data need to get transpose
Table query:
drop table ##Test
CREATE TABLE ##Test
(paymentid varchar(30),
claimid bigint,
Lineno1 int,
groupcode varchar(2),
Carc int,
adjustmentamt float,
RARC varchar(30),
Edit1 varchar(30),
Remit varchar(30),
)
INSERT INTO ##Test
(paymentid ,
claimid ,
Lineno1 ,
groupcode ,
Carc ,
adjustmentamt ,
RARC ,
Edit1 ,
Remit )
VALUES
('QP18502291',14205893514,2,'CO',84,75.55,'N20','','D18')
('QP15930339',14127612308,1,'OA',23,263,'','ClaimDetail.COBAmt','') ,
('QP15930339',14127612308,1,'OA',23,21.69,'','ClaimDetail.COBAmt',''),
('QP18502291',14205893514,2,'OA',23,78.77,'','ClaimDetail.COBAmt',''),
('QP18502291',14205893514,2,'OA',97,66.55,'N20','','D18')
select * from ##Test
Possible duplicate post and take a look at the solution.
See SQL Fiddle with Demo.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(col+cast(rn as varchar(10)))
from
(
select row_number() over(partition by paymentid order by Lineno1) rn
from ##Test
) d
cross apply
(
select 'groupcode', 1 union all
select 'carc', 2 union all
select 'adjustmentamt', 3 UNION ALL
SELECT 'rarc',4 UNION ALL
SELECT 'Edit1' ,5 UNION ALL
SELECT 'remit',6
) c (col, so)
group by col, rn, so
order by rn, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT paymentid, claimid,Lineno1,' + #cols + '
from
(
select paymentid, claimid,Lineno1, col+cast(rn as varchar(10)) col, value
from
(
select paymentid, claimid,Lineno1, groupcode, carc, adjustmentamt,rarc,Edit1,remit,
row_number() over(partition by paymentid order by Lineno1) rn
from ##Test
) t
cross apply
(
select ''groupcode'', groupcode union all
select ''carc'', cast(carc as varchar(50)) union all
select ''adjustmentamt'', cast(adjustmentamt as varchar(50)) union all
select ''rarc'', rarc union all
select ''Edit1'' , Edit1 union all
select ''remit'' , remit
) c (col, value)
) x pivot
(
max(value)
for col in (' + #cols + ')
) p '
execute(#query)

Adding a WHERE statement refering another table in Dynamic SQL

I currently have the following script which is pivoting results from rows into columns. It works a Great, apart from two issues;
I have a flag in another table which I want to filter by (basically: WHERE Table.Stats=YES). I'd normally do this in a basic query with an inner join followed by that WHERE statement. In the query below, I already have a WHERE FileSeq=25, which works, but this criteria I need to get working is calling on a different table.
The query is returning a lot of uncessary NULL fields.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME(col+CAST(rn AS varchar(6)))
FROM
(
SELECT row_number() over(partition by UID ORDER BY ClassCode) rn
FROM dbo.StudentClasses
) d
CROSS APPLY
(
SELECT 'ClassCode', 1
) c (col, so)
GROUP BY col, rn, so
ORDER BY rn, so
FOR XML PATH(''), TYPE
).VALUE('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT UID,' + #cols + '
FROM
(
SELECT UID, col+CAST(rn AS varchar(10)) col, VALUE
FROM
(
SELECT UID, classcode,
row_number() over(partition by UID ORDER BY classcode) rn
FROM StudentClasses WHERE FileSeq=25
) t
CROSS APPLY
(
SELECT ''classcode'', CAST(classcode AS varchar(6))
) c (col, VALUE)
) x
PIVOT
(
MAX(VALUE)
for col in (' + #cols + ')
) p '
EXECUTE(#query)
Any assistance appreciated

showing rows of table as columns based on some ID

I have a table like
ID option
1 optionA
1 optionB
1 optionC
1 optionD
And I want a result like:
ID A B C D
1 optionA optionB optionC optionD
What is the best way to do this?
Query which i have tried is
select * from TableName PIVOT (option for ID = 2674 )) as abc
this will not work since PIVOT expects aggregated function..
I have also tried COALESCE like this
declare #t table(num VARCHAR(100))
insert into #t
select choice FROM QuestionAnswers where QuestionID=2674
select num from #t
declare #s varchar(8000)
select #s = COALESCE(#s + ',', '') + num
from #t
exec('select '+#s)
but this doesn't work as well..
This type of data transformation is known as a pivot. In SQL Server 2005+ there is a function that will perform this data rotation for you. However, there are many ways that you can perform this data transformation.
Here is a PIVOT query that will work with your sample data:
select *
from
(
select id, [option], right([option], 1) col
from yourtable
) src
pivot
(
max([option])
for col in (a, b, c, d)
) piv
See SQL Fiddle with Demo.
This can also be performed using an aggregate function with a CASE expression:
select id,
max(case when col = 'a' then [option] else null end) a,
max(case when col = 'b' then [option] else null end) b,
max(case when col = 'c' then [option] else null end) c,
max(case when col = 'd' then [option] else null end) d
from
(
select id, [option], right([option], 1) col
from yourtable
) src
group by id
See SQL Fiddle with Demo.
You can perform multiple joins on your table:
select a.id,
a.[option] a,
b.[option] b,
c.[option] c,
d.[option] d
from yourtable a
left join yourtable b
on a.id = b.id
and right(b.[option], 1) = 'b'
left join yourtable c
on a.id = c.id
and right(c.[option], 1) = 'c'
left join yourtable d
on a.id = d.id
and right(d.[option], 1) = 'd'
where right(a.[option], 1) = 'a'
See SQL Fiddle with Demo
Lastly, this can be done using dynamic sql if the values to be turned into columns is unknown:
DECLARE #colsName AS NVARCHAR(MAX),
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #colsName = STUFF((SELECT distinct ', ' + QUOTENAME(right([option], 1)) +' as '+ right([option], 1)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select #cols = STUFF((SELECT distinct ', ' + QUOTENAME(right([option], 1))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT id, ' + #colsName + ' from
(
select id, [option], right([option], 1) col
from yourtable
) x
pivot
(
max([option])
for col in (' + #cols + ')
) p '
execute(#query)
See SQL Fiddle with Demo
The result of all queries is:
| ID | A | B | C | D |
----------------------------------------------
| 1 | optionA | optionB | optionC | optionD |
CREATE TABLE Product(Cust VARCHAR(25), Product VARCHAR(20), QTY INT)
GO
-- Inserting Data into Table
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','VEG',2)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','SODA',6)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','MILK',1)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','BEER',12)
INSERT INTO Product(Cust, Product, QTY)
VALUES('FRED','MILK',3)
INSERT INTO Product(Cust, Product, QTY)
VALUES('FRED','BEER',24)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','VEG',3)
GO
-- Selecting and checking entires in table
SELECT *
FROM Product
GO
-- Pivot Table ordered by PRODUCT
SELECT PRODUCT, FRED, KATE
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT (SUM(QTY) FOR CUST IN (FRED, KATE)) AS pvt
ORDER BY PRODUCT
GO
-- Pivot Table ordered by CUST
SELECT CUST, VEG, SODA, MILK, BEER, CHIPS
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT (SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt
ORDER BY CUST
GO
-- Unpivot Table ordered by CUST
SELECT CUST, PRODUCT, QTY
FROM
(
SELECT CUST, VEG, SODA, MILK, BEER, CHIPS
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT
( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p
UNPIVOT
(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)
) AS Unpvt
GO
-- Clean up database
DROP TABLE Product
GO
Ref http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
Edited
DECLARE #Product TABLE (ID int, _option varchar(10) )
-- Inserting Data into Table
INSERT INTO #Product
(
ID,
_option
)
SELECT 1, 'optionA' UNION ALL
SELECT 1, 'optionB' UNION ALL
SELECT 1, 'optionC' UNION ALL
SELECT 1, 'optionD'
SELECT
optionA, optionB, optionC, optionD
FROM (
SELECT ID, _option
FROM #Product) up
PIVOT (SUM(ID) FOR _option IN (optionA, optionB, optionC, optionD)) AS pvt

SQL FORCE SORT Columns generated from rows by values contained

I have a requirement to order the output of a dynamic query, that turns columns into rows, to ensure that only columns with values are generated before the rows with no values. How do I force order on the generation of the columns so the first columns are columns that contain values for particular fields while those with no values for the particular fields are generated at the end of my row?
insert into #PriceSheet
select ID, ProductID,SheetNumber ,SheetDesc ,MfgPriceCode,PriceZone
FROM ProductPrice
left join UNITS On SUOM = UOMID
select #colsUnpivot = stuff((select ','+quotename(C.name)
from tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#PricingSheet') and
C.name LIKE '%%'
for xml path('')), 1, 1, '')
select #colsPivot = STUFF((SELECT ','
+ quotename(c.name
+ cast(t.rn as varchar(10)))
from
(
select row_number() over(partition by ProductID
order by ProductID) rn
from #PriceSheet
) t
cross apply
tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#PricingSheet')
and C.name Not in ('CreateDate', 'LastModifiedDate')
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'select *
from
(
select ProductID, col + cast(rn as varchar(10)) new_col, val
from
(
select
cast(ProductID as varchar(50))ProductID
,cast(SheetNumber as varchar(50))SheetNumber
,cast(SheetDesc as varchar(50))SheetDesc
,cast(MfgPriceCode as varchar(50))MfgPriceCode
,cast(PriceZone as varchar(50))PriceZone
row_number() over(partition by productid order by productid) rn
from #PriceSheet
) x
unpivot
(
val
for col in ('+ #colsunpivot +')
) u
) x1
pivot
(
max(val)
for new_col in
('+ #colspivot +')
) p'
Say for instance, to generate the columns first for rows that have SheetNumber not equal to NULL and then the NULLS afterward.
select *
from
(
select ProductID,
col + cast(rn as varchar(10)) new_col,
val
from
(
select
Cast (ProductID as NVarchar(3072)) ProductID
,Cast (SheetNumber as NVarchar(3072)) SheetNumber
,Cast (SheetDesc as NVarchar(3072)) SheetDesc
,Cast (MfgPriceCode as NVarchar(3072)) MfgPriceCode
,Cast (PriceZone as NVarchar(3072)) PriceZone
,row_number() over(partition by ProductID order by Case When SheetNumber Is Null Then 1 Else 0 End, ProductID) rn
from MainPricesheet
) x
unpivot
(
val
for col in ([SheetNumber],[SheetDesc],[MfgPriceCode],[PriceZone])
) u
) x1
pivot
(
max(val)
for new_col in
([SheetNumber1],[SheetDesc1],[MfgPriceCode1],[PriceZone1],
[SheetNumber2],[SheetDesc2],[MfgPriceCode2],[PriceZone2],
[SheetNumber3],[SheetDesc3],[MfgPriceCode3],[PriceZone3],
[SheetNumber4],[SheetDesc4],[MfgPriceCode4],[PriceZone4],
[SheetNumber5],[SheetDesc5],[MfgPriceCode5],[PriceZone5],
[SheetNumber6],[SheetDesc6],[MfgPriceCode6],[PriceZone6],
[SheetNumber7],[SheetDesc7],[MfgPriceCode7],[PriceZone7],
[SheetNumber8],[SheetDesc8],[MfgPriceCode8],[PriceZone8],
[SheetNumber9],[SheetDesc9],[MfgPriceCode9],[PriceZone9],
[SheetNumber10],[SheetDesc10],[MfgPriceCode10],[PriceZone10],
[SheetNumber11],[SheetDesc11],[MfgPriceCode11],[PriceZone11],
[SheetNumber12],[SheetDesc12],[MfgPriceCode12],[PriceZone12],
[SheetNumber13],[SheetDesc13],[MfgPriceCode13],[PriceZone13],
[SheetNumber14],[SheetDesc14],[MfgPriceCode14],[PriceZone14],
[SheetNumber15],[SheetDesc15],[MfgPriceCode15],[PriceZone15],
[SheetNumber16],[SheetDesc16],[MfgPriceCode16],[PriceZone16],
[SheetNumber17],[SheetDesc17],[MfgPriceCode17],[PriceZone17],
[SheetNumber18],[SheetDesc18],[MfgPriceCode18],[PriceZone18],
[SheetNumber19],[SheetDesc19],[MfgPriceCode19],[PriceZone19],
[SheetNumber20],[SheetDesc20],[MfgPriceCode20],[PriceZone20],
[SheetNumber21],[SheetDesc21],[MfgPriceCode21],[PriceZone21])
) p