【问题标题】:Finding orders where products of both types are present查找同时存在两种类型产品的订单
【发布时间】:2020-12-28 00:31:11
【问题描述】:
考虑下表:
ordernr productId productType
1 12 A
2 15 B
2 13 C
2 12 A
3 15 B
3 12 A
3 11 D
我怎样才能只获取订单中同时存在 productType 的 B 和 C 的产品的行?
所需的输出应如下所示,因为 B 和 C 类型的产品都出现在订单中:
2 15 B
2 13 C
2 12 A
【问题讨论】:
标签:
sql
sql-server
tsql
count
subquery
【解决方案1】:
一种方法是使用 CTE 获取计数,然后使用外部查询中的计数进行过滤:
WITH CTE AS(
SELECT ordernr,
productId,
productType
COUNT(CASE productType WHEN 'B' THEN 1 END) AS BCount,
COUNT(CASE productType WHEN 'C' THEN 1 END) AS CCount
FROM dbo.YourTable)
SELECT ordernr,
productId,
productType
FROM CTE
WHERE BCount > 0
AND CCount > 0;
【解决方案2】:
您可以通过此查询获得所需的所有ordernrs:
select ordernr
from tablename
where productType in ('B', 'C')
group by ordernr
having count(distinct productType) = 2
所以你可以和运算符in一起使用:
select * from tablename
where ordernr in (
select ordernr
from tablename
where productType in ('B', 'C')
group by ordernr
having count(distinct productType) = 2
)
请参阅demo。
结果:
> ordernr | productId | productType
> ------: | --------: | :----------
> 2 | 15 | B
> 2 | 13 | C
> 2 | 12 | A
【解决方案3】:
使用两次exists 可能更有效:
select t.*
from mytable t
where
exists (select 1 from mytable t1 where t1.ordernr = t.ordernr and t1.productid = 'B')
and exists (select 1 from mytable t1 where t1.ordernr = t.ordernr and t1.productid = 'C')
此查询将利用(ordernr, productid) 上的索引。