0

我需要帮助构建一个 SQL 查询,该查询返回一个订单中前 2 个项目的扁平化结果。

表格及相关字段如下:

Order        OrderItem       
-------      -----------     
orderId      orderId         
             productCode     
             quantity

我正在寻找所需的结果集:

[orderId]    [productCode1]    [quantity1]    [productCode2]    [quantity2]
----------   --------------    -----------    --------------    -----------
o123         p134              3              p947              1   
o456         p384              2              p576              1   

结果将按orderIdfrom分组Order,TOP 2productCode来自quantityfrom OrderItem。我不在乎返回哪个 TOP 2,只需要任意两个。

任何帮助将不胜感激。

4

3 回答 3

0

您可以使用条件聚合和窗口函数来做到这一点row_number()

select orderId,
       max(case when seqnum = 1 then ProductCode end) as ProductCode1,
       max(case when seqnum = 1 then Quantity end) as Quantity1,
       max(case when seqnum = 2 then ProductCode end) as ProductCode2,
       max(case when seqnum = 2 then Quantity end) as Quantity2
from (select oi.*,
             row_number() over (partition by orderId order by quantity desc) as seqnum
      from OrderItem oi
     ) oi
group by orderId;
于 2013-08-21T19:43:37.540 回答
0

假设您正在使用SQL Server 2005或更高版本,您可以创建一个按 排序的 CTE ProductCode,然后在第二个 CTE 中获取排名为 2 的行并将join它们持续到Orders

;WITH OrderItem1 AS 
(
    SELECT OrderID, productCode AS productCode1, quantity AS quantity1,
        ROW_NUMBER() OVER (PARTITION  BY OrderID ORDER BY productCode) AS RowID
    FROM [OrderItem] 
), 
OrderItem2 AS 
(
    SELECT OrderID, productCode1 AS productCode2, quantity1 AS quantity2
    FROM [OrderItem1] 
    WHERE RowID = 2
)
SELECT [Order].OrderID, [OrderItem1].[productCode1], [OrderItem1].quantity1,
       [OrderItem2].productCode2, [OrderItem2].quantity2
FROM [Order]
INNER JOIN OrderItem1 ON [Order].OrderID = OrderItem1.OrderID
LEFT JOIN OrderItem2 ON [Order].OrderID = OrderItem2.OrderID
WHERE OrderItem1.RowID = 1 
于 2013-08-21T19:44:49.150 回答
0
select
    o.orderId,
    max(case when row_num = 1 then oi.ProductCode end) as ProductCode1,
    max(case when row_num = 1 then oi.Quantity end) as Quantity1,
    max(case when row_num = 2 then oi.ProductCode end) as ProductCode2,
    max(case when row_num = 2 then oi.Quantity end) as Quantity2
from Order as o
   outer apply (
       select top 2
           oi.*, row_number() over (order by oi.productCode) as row_num
       from OrderItem as oi
       where oi.orderId = o.orderId
   ) as oi
group by o.orderId
于 2013-08-21T20:06:14.617 回答