Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 查找存在两种类型产品的订单_Sql_Sql Server_Tsql_Count_Subquery - Fatal编程技术网

Sql 查找存在两种类型产品的订单

Sql 查找存在两种类型产品的订单,sql,sql-server,tsql,count,subquery,Sql,Sql Server,Tsql,Count,Subquery,考虑下表tbl: ordernr productId productType 112A 2 15 B 2 13 C 2 12 A 3 15 B 312A 311D 如何仅获取订单中同时存在productType的B和C产品的行? 由于订单中同时存在B型和C型产品,因此所需输出应如下所示: 2 15 B 2 13 C 2 12 A 一种方法是使用CTE获取计数,然后使用外部查询中的计数进行过滤: 以CTE为例 选择ordernr, productId, 产品类型 COUNTCASE product

考虑下表tbl:

ordernr productId productType 112A 2 15 B 2 13 C 2 12 A 3 15 B 312A 311D 如何仅获取订单中同时存在productType的B和C产品的行? 由于订单中同时存在B型和C型产品,因此所需输出应如下所示:

2 15 B 2 13 C 2 12 A
一种方法是使用CTE获取计数,然后使用外部查询中的计数进行过滤:

以CTE为例 选择ordernr, productId, 产品类型 COUNTCASE productType当“B”时,则1结束为BCount, COUNTCASE productType当“C”时,则1结束为Account 从dbo.YourTable 选择ordernr, productId, 产品类型 来自CTE 其中b计数>0 和CCount>0; 您可以通过此查询获取所需的所有OrderNR:

select ordernr
from tablename
where productType in ('B', 'C')
group by ordernr
having count(distinct productType) = 2
因此,您可以将其与中的运算符一起使用:

看。 结果:


使用两次可能更有效:

此查询将利用ordernr、productid上的索引

select * from tablename
where ordernr in (
  select ordernr
  from tablename
  where productType in ('B', 'C')
  group by ordernr
  having count(distinct productType) = 2
)
> ordernr | productId | productType
> ------: | --------: | :----------
>       2 |        15 | B          
>       2 |        13 | C          
>       2 |        12 | A          
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')