【问题标题】:SQL: Select count of accomplished invoices with all items checkedSQL:选择已检查所有项目的已完成发票计数
【发布时间】:2016-08-25 09:25:06
【问题描述】:

我的客户提交的发票中每张都包含一些物品。我想计算已完成发票的数量(所有项目均由操作员检查)

样本数据:

invoiceNumber    |     ItemNumber    |     Status
a                      1                    Null
a                      2                    checked
a                      3                    Null
b                      1                    checked
b                      5                    checked

在上面的示例数据中,已完成发票的数量为 1,因为发票编号 “B” 中的所有项目都已检查,未完成发票的数量为 1,因为发票 “A”,仅选中一项。

我的尝试:

select count(distinct invoiceNumber) as total 
from invoices 
where status is not null

返回 2!我不应该计算第 2 行,因为第 1 行和第 3 行仍然为 Null。

【问题讨论】:

  • 您使用的是哪个 DBMS?
  • 指定预期结果(使用与表格数据相同的格式。)
  • 预期结果不是记录集。我正在寻找“1”

标签: sql count distinct


【解决方案1】:

使用下面的查询..

SELECT count(distinct invoiceNumber) as total
    FROM from invoices
        WHERE invoiceNumber    NOT IN (SELECT invoiceNumber
    FROM  invoices  WHERE status IS null)

【讨论】:

    【解决方案2】:

    您需要排除具有相同发票编号的NULL 状态的所有发票:

    select count(distinct i1.invoicenumber)
    from invoices i1
    where not exists (select *
                      from invoices i2
                      where i2.invoicenumber = i1.invoicenumber
                      and i2.status is null);
    

    另一种选择是使用except 删除那些状态为空的:

    select count(*)
    from (
      select invoicenumber
      from invoices
      except
      select invoicenumber
      from invoices
      where status is null
    );
    

    【讨论】:

      【解决方案3】:

      distinct 是问题所在,因为您计算了 invoiceNumber 的独特外观作为结果。由于检查了两个bs 和一个a,因此计数为2

      尝试改用select count (*) 或发票的一些唯一ID(如果有的话)。

      编辑: 我误读了你的问题。要仅计算所有行的状态都已检查的发票,您可以使用group byhaving

      类似于:

      select count(distinct invoiceNumber) as total 
      from invoices 
      group by invoiceNumber, status 
      having status is not null
      

      【讨论】:

      • 这仍将在结果中包含 invoicenumber a
      猜你喜欢
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2013-10-01
      相关资源
      最近更新 更多