在SQL中将多行转置为列

时间:2014-05-22 17:59:40

标签: sql sql-server sql-server-2008

我有两张桌子。

Order                Order_Items
=====                ===========
order_id             order_item_id  
customer_id          order_id
                     item_id
                     qty
                     price

可以制作一个视图,该视图会返回一行中订单的所有项目吗?最多只能有5个项目

实施例

order_id customer_id item_id_1 qty_1 price_1 item_id_2 qty_2 price_2 ....
====================================================================
7845       235         123       1    25.00    NULL     NULL  NULL
7846       784         346       8     9.99     123        1   25.00   

2 个答案:

答案 0 :(得分:1)

这样做的一种方法是使用公用表表达式对行进行排名,然后只需将表连接5次以获取每个项目。您需要使用LEFT JOIN来确保您还获得没有填充所有5个广告位的订单。下面的查询只实现3个项目,接下来的2个是相当直接的;

WITH cte AS (
  SELECT a.order_id, a.customer_id, b.item_id, b.quantity, b.price,
  ROW_NUMBER() OVER (PARTITION BY a.order_id ORDER BY order_item_id) rn
  FROM orders a
  JOIN order_items b
    ON a.order_id = b.order_id
)
SELECT DISTINCT a.order_id, a.customer_id,
       b.item_id item_id_1, b.quantity qty_1, b.price price_1,
       c.item_id item_id_2, c.quantity qty_2, c.price price_2,
       d.item_id item_id_3, d.quantity qty_3, d.price price_3
FROM      cte a
JOIN      cte b ON a.order_id = b.order_id AND b.rn=1
LEFT JOIN cte c ON a.order_id = c.order_id AND c.rn=2
LEFT JOIN cte d ON a.order_id = d.order_id AND d.rn=3

An SQLfiddle to test with

答案 1 :(得分:1)

如果您的订单行项目从1顺序编号,您只需执行以下操作:

select customer_id = o.customer_id ,
       order_id    = o.order_id    ,
       item_id_1   = t1.item_id    , qty_1 = t1.qty , price_1 = t1.price ,
       item_id_2   = t2.item_id    , qty_2 = t2.qty , price_2 = t2.price ,
       item_id_3   = t3.item_id    , qty_3 = t3.qty , price_3 = t3.price ,
       item_id_4   = t4.item_id    , qty_4 = t4.qty , price_4 = t4.price ,
       item_id_5   = t5.item_id    , qty_5 = t5.qty , price_5 = t5.price ,
from dbo.Order      o
left join dbo.Order_Item t1 on i.order_item_id = 1 and i.order_id = o.order_id
left join dbo.Order_Item t2 on i.order_item_id = 2 and i.order_id = o.order_id
left join dbo.Order_Item t3 on i.order_item_id = 3 and i.order_id = o.order_id
left join dbo.Order_Item t4 on i.order_item_id = 4 and i.order_id = o.order_id
left join dbo.Order_Item t5 on i.order_item_id = 5 and i.order_id = o.order_id

如果没有,您需要做CTE路线。