【问题标题】:Using count to find number of occurrences of a value with a where clause使用 count 查找带有 where 子句的值的出现次数
【发布时间】:2016-03-06 21:25:20
【问题描述】:

我有这张桌子(这是一个简短的版本)

item_id    computer_type   operating_system
  1           PC             UNIX
  2           DESKTOP        OSX
  3           LAPTOP         WINDOWS
  4           DESKTOP        UNIX
  5           PC             OSX
  6           PC             WINDOWS

如何使用 SQL 确定表中运行“unix”的“桌面”计算机的数量?

【问题讨论】:

  • 没有更容易,请展示您尝试了什么?
  • SELECT computer_type, operating_system, count(*) FROM computer WHERE computer_type = 'DESKTOP' and operating_system ='UNIX' GROUP BYcomputer_type, operating_system;
  • 这是我认为最接近的,但我只得到了表中没有数据的列名
  • 该查询看起来应该可以工作 (sqlfiddle.com/#!9/297e0d/2)。你确定你有这些数据?或者您的预期结果是什么?
  • 我 100% 拥有该数据,因为如果我运行 SELECT * FROM 计算机,我会得到表格。但是,当我运行我之前发布的那个查询时,我只得到列名“computer_type”、“operating_system”和“count(*)”而没有数据,因为我期望 1 个条目包含运行 Unix 的桌面数量

标签: sql oracle count where


【解决方案1】:
Select count(1)
from table
where computer_type = 'DESKTOP'
and operating_system = 'UNIX'

【讨论】:

    【解决方案2】:
    SELECT computer_type,
           operating_system,
           count(*)
    FROM   computers
    WHERE  computer_type    = 'DESKTOP'
    AND    operating_system = 'UNIX'
    GROUP BY
           computer_type,
           operating_system;
    

    这假定COMPUTER_TYPEOPERATING_SYSTEM 列的类型为VARCHAR2(如果使用DESCRIBE computers; 命令,您可以看到)。如果它们的类型为CHAR,那么它们将在右侧填充空格字符,您可以使用:

    SELECT computer_type,
           operating_system,
           count(*)
    FROM   computers
    WHERE  RTRIM( computer_type )    = 'DESKTOP'
    AND    RTRIM( operating_system ) = 'UNIX'
    GROUP BY
           computer_type,
           operating_system;
    

    或者,您可以将字符串文字右填充适当的长度:

    SELECT computer_type,
           operating_system,
           count(*)
    FROM   computers
    WHERE  computer_type    = 'DESKTOP        '
    AND    operating_system = 'UNIX           '
    GROUP BY
           computer_type,
           operating_system;
    

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2013-10-11
      • 2018-03-06
      相关资源
      最近更新 更多