SQL FORCE SORT Columns generated from rows by values contained - sql

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

Related

how to display data with dynamic columns -SQL

I have a dynamic pivot query that has dynamic columns column1, column 2... column
My query works fine. I can dump it into temp table ... But I wanted a view. I can't because of the changing number of columns. What do I do? It took long time to put this query together as I am not sql expert.
I would like to have a view of the result so I can link it to Access for the teams. I also have to create more queries in Access based on this link so the link can not disconnect. Any help will be appreciated
Below is my query.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ','
+ QUOTENAME(case
when d.col = 'OriginalDx' then col+cast(seq as varchar(10))
else 'OriginalDx'+cast(seq as varchar(10))+'_'+col end)
from
(
select row_number() over(partition by [HCCCodingBASEID]
order by [HCCCodingBASEID]) seq
from [IDEAApplication].[HCCCoding].[OriginalDiagnosis]
) t
cross apply
(
select 'OriginalDx', 1
) d (col, so)
group by col, so, seq
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT [HCCCodingBASEID] AS ORIGINALDX_ID, ' + #cols + '
from
(
select t.[HCCCodingBASEID],
col = case
when c.col = ''OriginalDx'' then col+cast(seq as varchar(10))
else ''OriginalDx''+cast(seq as varchar(10))+''_''+col
end,
value
from
(
select [HCCCodingBASEID], [OriginalDiagnosisCD],
row_number() over(partition by [HCCCodingBASEID]
order by [HCCCodingBASEID]) seq
from [IDEAApplication].[HCCCoding].[OriginalDiagnosis]
) t
cross apply
(
select ''OriginalDx'', [OriginalDiagnosisCD]
) c (col, value)
) x
pivot
(
max(value)
for col in (' + #cols + ')
) p '
----execute sp_executesql #query;
DECLARE #cols1 AS NVARCHAR(MAX),
#query1 AS NVARCHAR(MAX)
select #cols1 = STUFF((SELECT ','
+ QUOTENAME(case
when d.col = 'DxAdded' then col+cast(seq as varchar(10))
else 'DxAdded'+cast(seq as varchar(10))+'_'+col end)
from
(
select row_number() over(partition by [HCCCodingBASEID]
order by [AddDiagnosisCD]) seq
from [IDEAApplication].[HCCCoding].[AddDiagnosis]
) t1
cross apply
(
select 'DxAdded', 1 union all
select 'Reason', 2
) d (col, so)
group by col, so, seq
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query1 = 'SELECT [HCCCodingBASEID] AS DXADDED_ID, ' + #cols1 + '
from
(
select t1.[HCCCodingBASEID],
col = case
when c.col = ''DxAdded'' then col+cast(seq as varchar(10))
else ''DxAdded''+cast(seq as varchar(10))+''_''+col
end,
value
from
(
select [HCCCodingBASEID], [AddDiagnosisCD], [AddReasonTXT],
row_number() over(partition by [HCCCodingBASEID]
order by [AddDiagnosisCD]) seq
from [IDEAApplication].[HCCCoding].[AddDiagnosis]
) t1
cross apply
(
select ''DxAdded'', [AddDiagnosisCD] union all
select ''Reason'', [AddReasonTXT]
) c (col, value)
) x
pivot
(
max(value)
for col in (' + #cols1 + ')
) p '
------------------------------------------------------------------
DECLARE #cols2 AS NVARCHAR(MAX),
#query2 AS NVARCHAR(MAX)
select #cols2 = STUFF((SELECT ','
+ QUOTENAME(case
when d.col = 'DxDeleted' then col+cast(seq as varchar(10))
else 'DxDeleted'+cast(seq as varchar(10))+'_'+col end)
from
(
select row_number() over(partition by [HCCCodingBASEID]
order by [DeleteDiagnosisCD]) seq
from [IDEAApplication].[HCCCoding].[DeleteDiagnosis]
) t2
cross apply
(
select 'DxDeleted', 1 union all
select 'Reason', 2
) d (col, so)
group by col, so, seq
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query2 = 'SELECT [HCCCodingBASEID] AS DXDELETED_ID, ' + #cols2 + '
-----into ##tmp2
from
(
select t2.[HCCCodingBASEID],
col = case
when c.col = ''DxDeleted'' then col+cast(seq as varchar(10))
else ''DxDeleted''+cast(seq as varchar(10))+''_''+col
end,
value
from
(
select [HCCCodingBASEID], [DeleteDiagnosisCD], [DeleteReasonTXT],
row_number() over(partition by [HCCCodingBASEID]
order by [DeleteDiagnosisCD]) seq
from [IDEAApplication].[HCCCoding].[DeleteDiagnosis]
) t2
cross apply
(
select ''DxDeleted'', [DeleteDiagnosisCD] union all
select ''Reason'', [DeleteReasonTXT]
) c (col, value)
) x
pivot
(
max(value)
for col in (' + #cols2 + ')
) p '
-----------------------------------------------------merge all tables
----IF OBJECT_ID('tempdb..##TMP') IS NOT NULL
---DROP TABLE ##TMP
DECLARE #cmd NVARCHAR(MAX);
SET #cmd=N'
SELECT top 100 percent
A.*,
BB.PatientID as [Epic PatientID],
convert (varchar (10),AA.BirthDTS,101) as [Birth Date],
AA.SexDSC as [Sex],
BB.HospitalAccountBaseClassDSC as [Patient Type],
EE.payorNM AS [Payor Name],
B.*,
C.*,
D.*
--INTO ##TMP
FROM
[IDEAApplication].[HCCCoding].[HCCCoding] as A
LEFT JOIN ('+#query+') AS B
ON A.ID=B.ORIGINALDX_ID
LEFT JOIN ('+#query1+') AS C
ON A.ID=C.DXADDED_ID
LEFT JOIN ('+#query2+') AS D
ON A.ID=D.DXDELETED_ID
LEFT OUTER JOIN Epic.Finance.HospitalAccount_Enterprise AS BB
ON A.HospitalAccountID = BB.HospitalAccountID
LEFT JOIN Epic.Patient.Patient_Enterprise AS AA
ON BB.PatientID =AA.PatientID
LEFT JOIN Epic.Finance.HospitalAccount3_Enterprise AS CC
ON BB.HospitalAccountID = CC.HospitalAccountID
LEFT JOIN Epic.Reference.Payor AS EE
ON BB.PrimaryPayorID = EE.PayorID
order BY A.ID
;
';
EXECUTE (#cmd)

converting and concatenating multiple rows into columns

I am using Dynamic PIVOT approach to convert the dynamic rows into columns and its working fine for me. But I have one more requirement on top of it. I am using below query:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ','
+ QUOTENAME(case when d.col = 'STN_CODE' then col+'_'+cast(seq as varchar(10))
else col+'_'+cast(seq as varchar(10)) end)
from ( select row_number() over(partition by POF_FILE_ID,
PART_PFX,
PART_BASE,PART_SFX
order by STN_CODE,PROCESS_ELEMENT) seq
from APT_POINT_OF_FIT
) t
cross apply
(
select 'STN_CODE', 1 union all
select 'PROCESS_ELEMENT', 2
) d (col, so)
group by col, so, seq
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT POF_FILE_ID,PART_PFX,PART_BASE,PART_SFX, ' +
#cols + '
from
(
select t.POF_FILE_ID,t.PART_PFX,t.PART_BASE,t.PART_SFX,
col = case
when c.col = ''STN_CODE'' then col+''_''+cast(seq as varchar(10))
else col+''_''+cast(seq as varchar(10))
end,
value
from
(
select POF_FILE_ID,PART_PFX,PART_BASE,PART_SFX,STN_CODE,
PROCESS_ELEMENT,
row_number() over(partition by POF_FILE_ID,
PART_PFX,
PART_BASE,
PART_SFX
order by STN_CODE) seq
from APT_POINT_OF_FIT
) t
cross apply
(
select ''STN_CODE'', STN_CODE union all
select ''PROCESS_ELEMENT'', PROCESS_ELEMENT
) c (col, value)
) x
pivot
(
max(value)
for col in (' + #cols + ')
) p '
execute sp_executesql #query;
My requirement is to insert the values in separate columns till seq 8 and concatenate all other column values coming after that seq(> seq8).
Any help would be appreciated.
Thanks!

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

SQL Server- PIVOT table. transform row into columns

I am trying to convert rows into columns. here is my query
SELECT M.urn,
M.eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
N.time
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
AND M.eventcode = 'TFRADMIN'
Current result
URN Date Location Room Bed Time
F1002754364 20121101 EDEXPRESS 4-152 02 0724
F1002754364 20121101 CARDSURG 3-110 02 1455
F1002754364 20121102 CHEST UNIT 6-129-GL04 1757
required result
F1002754364 20121101 EDEXPRESS 4-152 02 0724 20121101 CARDSURG 3-110 02 1455 20121102 CHEST UNIT 6-129-GL 04 1757
Thanks for your help.
Since you are using SQL Server you can use both the UNPIVOT and PIVOT functions to transform this data. If you know how many values to you will have then you can hard-code the values similar to this:
select *
from
(
select urn,
value,
col +'_'+ CAST(rn as varchar(10)) as col
from
(
SELECT M.urn,
cast(M.eventdate as varchar(50)) eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
cast(N.time as varchar(50)) time,
ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
AND M.eventcode = 'TFRADMIN'
) src1
unpivot
(
value
for col in (eventdate, eventlocation, eventroom, eventbed, time)
) unpiv
) src2
pivot
(
max(value)
for col in ([eventdate_1], [eventlocation_1], [eventroom_1], [eventbed_1], [time_1],
[eventdate_2], [eventlocation_2], [eventroom_2], [eventbed_2], [time_2],
[eventdate_3], [eventlocation_3], [eventroom_3], [eventbed_3], [time_3])
) piv
Note- not tested
If you have an unknown number of columns, then you can use dynamic sql similar to this:
DECLARE #query AS NVARCHAR(MAX),
#colsPivot as NVARCHAR(MAX)
select #colsPivot = STUFF((SELECT ','
+ quotename(c.name +'_'+ cast(t.rn as varchar(10)))
from
(
select ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
) t
cross apply sys.columns as C
where C.object_id IN (object_id('admpatevents'), object_id('admpattransferindex')) and
C.name not in ('urn') -- add any other columns your want to exclude
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'select *
from
(
select urn, value, col +''_''+ CAST(rn as varchar(10)) as col
from
(
SELECT M.urn,
cast(M.eventdate as varchar(20)) eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
cast(N.time as varchar(20)) time,
ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.EVENTseqno
AND M.eventdate = N.eventdate
WHERE M.urn = ''F1002754364''
) x
unpivot
(
value
for col in (eventdate, eventlocation, eventroom, eventbed, time)
) u
) x1
pivot
(
max(value)
for col in ('+ #colspivot +')
) p'
exec(#query)
See SQL Fiddle with Demo

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

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...