SQL - 当两行或更多行的值满足条件时返回值
SQL - returning values when a condition is met for that value over two or more rows
我有两个数据tables -
订单级别:
Order_number | order total | etc
Order_num1 |
Order_num2 |
订单项级别:
Order_number | sku | quantity | etc
Order_num1 | sku1 | 3
Order_num1 | sku2 | 2
Order_num2 | sku1 | 4
等等。
我正在尝试编写一个 returns 任何 Order_numX 包含 skuY 和 skuZ 的查询。
我正在考虑以某种方式对订单项进行分组 table,但我不确定。
感谢任何帮助!谢谢。
所以我建议你使用 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'
)
此查询为您提供子 table 的 sku
列的 skuY
和 skuZ
值的订单,这里是 line-item
您可以使用聚合和 having
:
select order_number
from line_item
where sku in (?, ?)
group by order_number
having count(distinct sku) = 2; -- number of items in list
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
我有两个数据tables -
订单级别:
Order_number | order total | etc
Order_num1 |
Order_num2 |
订单项级别:
Order_number | sku | quantity | etc
Order_num1 | sku1 | 3
Order_num1 | sku2 | 2
Order_num2 | sku1 | 4
等等。
我正在尝试编写一个 returns 任何 Order_numX 包含 skuY 和 skuZ 的查询。
我正在考虑以某种方式对订单项进行分组 table,但我不确定。
感谢任何帮助!谢谢。
所以我建议你使用 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'
)
此查询为您提供子 table 的 sku
列的 skuY
和 skuZ
值的订单,这里是 line-item
您可以使用聚合和 having
:
select order_number
from line_item
where sku in (?, ?)
group by order_number
having count(distinct sku) = 2; -- number of items in list
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