首页 > 解决方案 > TSQL:给定一组 ID,获取所有标头,使得该集包含在标头的子项中

问题描述

我正在寻找一个查询,该查询将返回包含一组产品 ID 的所有订单 ID,但可能包含更多产品。

数据结构:

CREATE TABLE dbo.Order(OrderID int, OrderDesc nvarchar(100))
CREATE TABLE dbo.OrderDetail(DetailID int, OrderID int, ProductID int)
CREATE TABLE dbo.Product(ProductID INT, ProductDesc nvarchar(100))

因此,给定一组 productID,我想要一个查询来返回包含该集合中所有(可能更多)产品的所有订单。

标签: sqlsql-servertsql

解决方案


您可以使用聚合:

select od.orderid
from orderdetail od
where od.productId in (. . .)
group by od.orderid
having count(od.productid) = <n>;   -- <n> is the number of products in the list

这假设订单中没有重复的产品。如果可能,请使用count(distinct od.productid).


推荐阅读