【问题标题】:querying using count使用计数查询
【发布时间】:2014-11-30 23:12:56
【问题描述】:

我有以下数据库:

库存(StockNo、Storecode、Description、Quantity、Units、Reorder、 价格,SuppCode)

这是其中包含的数据示例:

STOCKNO STOREC DESCRIPTION             QUANTITY UNITS  REORDER   PRICE SUPPCO
------- ------ ----------------------- -------- ------ ------- ------- ------
    126 LEG    Sealing wax                    9 Box          5    7.99 S5
    127 LEG    Red binding ribbon            13 Roll        10    6.47 S5
    128 LEG    A3 cream notary paper         21 Ream        10    7.85 S5
    129 LEG    Coloured ink                  22 Bottle      10    3.48 S4

我需要查询以显示供应至少 3 家商店的供应商(供应代码)。

这是我目前所拥有的:

select suppcode, count(distinct storecode) as StoresSupplied
from stocks
group by suppcode
having count(*) > 3

这会产生以下结果

SUPPCO STORESSUPPLIED
------ --------------
S3                  4
S4                  3
S2                  3
S1                  1

检查整个表格,S3、S4 和 S2 的结果是正确的,但我找不到 S1 存在的任何原因。 S1 出现在桌子上,提供 8 种不同的物品,但只提供 1 个单独的商店代码。

【问题讨论】:

  • 如果将count(*) > 3 更改为count(distinct storecode) > 3 会怎样?
  • .......having count(*) > 3 ?
  • 附带说明,谓词 at least 3 等同于 >= 3,而不是 > 3(超过 3 个),这将排除供应 3 个商店的供应商。

标签: sql oracle


【解决方案1】:

Count(*) 将包含 Null 行,而 count(distinct storecode) 不会。试试这样改

select suppcode, count(distinct storecode) as StoresSupplied
from stocks
group by suppcode
having count(distinct storecode) > 3

【讨论】:

    【解决方案2】:

    我建议您只使用来自select 的别名:

    select suppcode, count(distinct storecode) as StoresSupplied
    from stocks
    group by suppcode
    having StoresSupplied > 3;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2019-02-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      相关资源
      最近更新 更多