SQL - 划分聚合字段,对 SQL 来说非常新

SQL - Dividing aggregated fields, very new to SQL

我有发票中的行项目列表,其中有一个字段指示行是已交付还是已提取。我需要从总行数中找到已交付项目的百分比。

SALES_NBR |总计 |送货率

1 = 已交付 0 = 从 FULFILLMENT 取货。

SELECT SALES_NBR, 
COUNT (ITEMS) as Total, 
SUM (case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
(SELECT delivered/total) as Deliveryrate
FROM Invoice_table
WHERE STORE IN '0123'
And SALE_DATE >='2020-02-01'
And SALE_DATE <='2020-02-07'
Group By SALES_NBR, Deliveryrate;

我的查询已执行但由于某种原因从未完成。有没有更简单的方法来做到这一点?履行字段不包含任何 NULL 值。

如有任何帮助,我们将不胜感激。

如果你想得到一个"nice"查询,你可以使用这样的子查询:

select
  qry.*,
  qry.delivered/qry.total as Deliveryrate
from (
  select 
    SALES_NBR, 
    count(ITEMS) as Total, 
    sum(case when FULFILLMENT = '1' then 1 else 0 end) as delivered
  from Invoice_table
  where STORE IN '0123'
    and SALE_DATE >='2020-02-01'
    and SALE_DATE <='2020-02-07'
  group by SALES_NBR
  ) qry;

但我认为这个,即使更丑陋,也可以执行得更快:

  select 
    SALES_NBR, 
    count(ITEMS) as Total, 
    sum(case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
    sum(case when FULFILLMENT = '1' then 1 else 0 end)/count(ITEMS) as Deliveryrate
  from Invoice_table
  where STORE IN '0123'
    and SALE_DATE >='2020-02-01'
    and SALE_DATE <='2020-02-07'
  group by SALES_NBR

I need to find a percentage of delivered items from the total number of lines.

最简单的方法是使用avg():

select SALES_NBR, 
       avg(fulfillment) as delivered_ratio
from Invoice_table
where STORE = '0123' and
      SALE_DATE >='2020-02-01' and
      SALE_DATE <='2020-02-07'
group by SALES_NBR;

我不确定是否需要 group by sales_nbr。