Sample Header Ad - 728x90

SQL Pivot table splitting rows on custom column names. I need 1 row per OrderId

0 votes
1 answer
111 views
I have this PIVOT table below. I have to dynamically create column headings based on the itemid value (1 to 50) in each order. then horizontally list them. in this example, it works, but it splits the rows. what can I do to change that and group them? I feel I missing one thing here and can't figure it out. If I comment out the ProductDesc pieces, it behaves correctly with just item1.item_id and item2.item_id which displays the SKU horizontally. Now I need item1.item_name and item2.item_name to display next to the item_id's horizontally. In this example, I achieve that, but lines are split. any help would be greatly appreciated Results currently that need to group up into 1 row CREATE TABLE #table1 (orderid nvarchar(256), itemid varchar(10),productid nvarchar(256), ProductDesc varchar(max)) insert into #table1 values ('001323232','1','ABC30013', 'LOVESEAT 3PC'), ('001323232','2','DFE30013', 'SOFA DINING SET') --select * from #table1 Select* From ( Select 'HG-KKSHGSRMN1XHG'as measurement_id , 'purchase' as event_name , 'https://www.test.com/ ' as [event_param.page_hostname], '1665100800' as timestamp_micros, 'offline' as [event_param.campaign_name], 'In-Store Sales' as [event_param.campaign_source] , 'item'+cast(Itemid as varchar) + '.item_id' as ItemId_ProductId , OrderId, ProductId as ProductId, -- ItemId as ItemId ProductDesc as ProductDesc, -- concat('item',row_number() over (partition by Orderid order by productid)) as ItemId_ProductId, -- 'item'+cast(Itemid as varchar) + '.item_name' as ItemId_ProductDesc 'item'+cast(Itemid as varchar) + '.item_name' as ItemId_ProductDesc -- ROW_NUMBER() OVER(ORDER BY cast(itemid as int) ASC) AS ItemId_ProductDesc FROM #table1 ) src PIVOT ( MAX(ProductId) For ItemId_ProductId in ([item1.item_id], [item2.item_id] ) ) mypivot PIVOT ( MAX(ProductDesc) For ItemId_ProductDesc in ([item1.item_name], [item2.item_name] ) ) mypivot2
Asked by paygboy00 (1 rep)
May 15, 2024, 03:10 PM
Last activity: May 15, 2024, 07:25 PM