如何解决查找同时存在两种类型产品的订单
请考虑下表tbl:
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
解决方法
一种方法是使用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,productType
FROM CTE
WHERE BCount > 0
AND CCount > 0;
,
两次使用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)
上的索引。
通过此查询,您可以获取所有需要的ordernr
:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。