如果至少只有一条记录,我需要找到与供应商编号 (SNo) 相关的所有记录 (Qty) 的平均值

I need to find the average of all records (Qty) which related Supplier numbers (SNo) if there have at least only one record

我需要找到与供应商编号 (SNo) 相关的所有记录 (Qty) 的平均值,如 S1、S2 等。即使至少只有一条记录满足条件

本次查询select只有一条记录和取平均值前的查询检查条件

select Sno, avg(qty) avg_qty                                              
from Supplier                                                       
group by  sno                             
having  avg(qty) > 50 and avg(qty) < 100

这是我的 table :

create table Supplier
(
SNo Varchar (5),
PNo Varchar (5),
JNo Varchar (5),
Qty int
)
Insert into Supplier values ('S1','P1','J1',50)
Insert into Supplier values ('S1','P1','J2',90)
Insert into Supplier values ('S1','P2','J1',40)
Insert into Supplier values ('S1','P3','J3',20)
Insert into Supplier values ('S2','P1','J3',110)
Insert into Supplier values ('S2','P2','J2',30)
Insert into Supplier values ('S2','P4','J3',10)
Insert into Supplier values ('S3','P3','J1',100)
Insert into Supplier values ('S3','P1','J3',80)
Insert into Supplier values ('S3','P4','J2',70)
Insert into Supplier values ('S4','P2','J1',60)
Insert into Supplier values ('S4','P1','J3',20)

我需要 select 来自 table 的平均数量,其中超过 50 个且少于 100 个。但我的查询 select 仅记录。
但我需要将结果作为:

S1 - 50 
S3 - 83 
S4 - 40 

所以 S2 没有任何介于 50 和 100 之间的数量。所以这就是它应该被拒绝的原因。

您需要检查 HAVING 子句是否有满足条件的供应商行:

select Sno, avg(qty) avg_qty                                              
from Supplier
group by  sno
having count(case when qty > 50 and qty < 100 then 1 end) > 0

参见demo
结果:

> Sno | avg_qty
> :-- | ------:
> S1  |      50
> S3  |      83
> S4  |      40