我需要帮助构建一个SQL查询,该查询返回订单中前2项的展平结果。
表格和相关字段如下:
Order OrderItem
------- -----------
orderId orderId
productCode
quantity
我正在寻找所需的结果集:
[orderId] [productCode1] [quantity1] [productCode2] [quantity2]
---------- -------------- ----------- -------------- -----------
o123 p134 3 p947 1
o456 p384 2 p576 1
结果将按orderId
的{{1}}分组,Order
的{{1}}来自productCode
。我不在乎哪个TOP 2会被退回,只需要两个。
非常感谢任何帮助。
答案 0 :(得分: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;
答案 1 :(得分:0)
假设您正在使用SQL Server 2005
或更高版本,您可以创建由ProductCode
排序的CTE,然后在第二个CTE中将排名为2且最后join
的行带到{{1 }}
Orders
答案 2 :(得分: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