SQL-在两行或更多行中满足该条件的条件时返回值

时间:2019-08-19 20:32:07

标签: sql database group-by uniqueidentifier

我有两个数据表-

订单级别:

Order_number | order total | etc
Order_num1   | $10
Order_num2   | $20

和订单项级别:

Order_number | sku  | quantity | etc    
Order_num1   | sku1 | 3    
Order_num1   | sku2 | 2    
Order_num2   | sku1 | 4

以此类推。

我正在尝试编写一个查询,该查询返回包含skuY和skuZ的所有Order_numX。

我正在考虑以某种方式对订单项表格进行分组,但不确定。

感谢您的帮助!谢谢。

3 个答案:

答案 0 :(得分:0)

所以我建议您使用EXISTS函数:

SELECT *
FROM Order
WHERE EXISTS(SELECT 1
             FROM line-item
             WHERE line-item.Order_number=Order.Order_number
             AND line-item.sku='skuY'
             )
AND EXISTS(SELECT 1
             FROM line-item
             WHERE line-item.Order_number=Order.Order_number
             AND line-item.sku='skuZ'
             )

此查询为您提供同时具有子表skuY列的skuZ列的skuline-item值的订单。

答案 1 :(得分:0)

您可以使用聚合和having

select order_number
from line_item
where sku in (?, ?)
group by order_number
having count(distinct sku) = 2;  -- number of items in list

答案 2 :(得分:0)

SELECT Order_number 
FROM line_item 
GROUP BY Order_number 
HAVING COUNT( CASE WHEN sku = skuY THEN 1 END) > 0
   AND COUNT( CASE WHEN sku = skuZ THEN 1 END) > 0