2017-03-01 39 views
0

我知道這個主題已經很好地暴露在這裏,但我相信我有一個特定的案例,到目前爲止我沒有找到任何解決方案。多行重複行到列

我有以下結果集:

Tp_Parameter Value  Order_Id 
------------ -----  --------  
Colour   Black  3824 
Size   S   3824 
Qty    2   3824 
ItemId   101   3824 
Colour   White  3824 
Size   M   3824 
Qty    1   3824 
ItemId   102   3824 
Colour   Red   3824 
Size   L   3824 
Qty    4   3824 
ItemId   105   3824 

而且我正在尋找設置這樣的結果:

Order_Id ItemId Colour Size Qty 
-------- ------ ------ ---- --- 
3824  101  Black S  2 
3824  102  White M  1 
3824  105  Red  L  4 

我試着支點,但我不能」處理它必須使用聚合函數的事實,哪一個會導致一行結果集(只有MAX或MIN等)

你能幫忙嗎?我呢?

+0

爲什麼101是黑色,S,2? – McNets

+0

這些值之間的關係是什麼? – McNets

+2

特定的'ItemId'和'Colour'之間沒有邏輯連接。 「Black」顏色可以屬於任何ItemIds。看起來你只是依賴於它們當前在那裏顯示的順序,但這不適用於默認排序將基於聚簇索引的SQL表中。 – Mitch

回答

0

你可以試試這個方法也

declare @t table(Tp_Parameter varchar(50) 
,Value varchar(50),Order_Id int) 

insert into @t VALUES 

('Colour' ,'Black',3824) 
,('Size' ,'S',3824) 
,('Qty' ,'2',3824) 
,('ItemId' ,'101',3824) 
,('Colour' ,'White',3824) 
,('Size' ,'M',3824) 
,('Qty' ,'1',3824) 
,('ItemId' ,'102',3824) 
,('Colour' ,'Red',3824) 
,('Size' ,'L',3824) 
,('Qty' ,'4',3824) 
,('ItemId' ,'105',3824) 
;with CTE as 
(
select *,ROW_NUMBER()over(order by (select NULL))rn 
from @t 
) 
select * 
,(select top 1 value from cte b 
where tp_parameter='ItemId' and b.rn>=a.rn order by rn)MissingItemid 
from cte a 

--now apply dynamic pivot so that you do not have to hard code parameter 
+0

是的,這對我來說非常有用。關鍵是「ItemId」作爲列(missingItemId)。非常感謝你 – RBara

1

讓我假設每行都有一個唯一的,增加的id。然後我們可以說特定的「ItemId」完成了該項目的行。

如果是這樣的:

select order_id, 
     max(case when tp_parameter = 'ItemId' then value end) as ItemId, 
     max(case when tp_parameter = 'Colour' then value end) as Colour, 
     max(case when tp_parameter = 'Size' then value end) as Size, 
     max(case when tp_parameter = 'Qty' then value end) as Qty 
from (select t.*, 
      sum(case when tp_parameter = 'ItemId' then 1 else 0 end) over (partition by order_id order by <id> desc) as item_grp 
     from t 
    ) t 
group by item_grp, order_id;