sql - 同一列上的不同值计数

标签 sql oracle pivot-table

我是 Oracle 的新手。我有一个包含三列的 Oracle 表:serialno , item_categoryitem_status .在第三列中,行的值为 serviceable , under_repaircondemned .

我想使用 count 运行查询以显示有多少是可维修的,有多少正在维修,有多少是针对每个项目类别的。

我想运行类似的东西:

select item_category
  , count(......) "total"
  , count (.....) "serviceable"
  , count(.....)"under_repair"
  , count(....) "condemned"
from my_table
group by item_category ......

我无法在计数内运行内部查询。

这是我希望结果集的样子:
item_category    total    serviceable      under repair      condemned
=============    =====    ============     ============      ===========
chair              18        10               5                3
table              12        6                3                3 

最佳答案

您可以在 COUNT 函数内使用 CASE 或 DECODE 语句。

  SELECT item_category,
         COUNT (*) total,
         COUNT (DECODE (item_status, 'serviceable', 1)) AS serviceable,
         COUNT (DECODE (item_status, 'under_repair', 1)) AS under_repair,
         COUNT (DECODE (item_status, 'condemned', 1)) AS condemned
    FROM mytable
GROUP BY item_category;

输出:
ITEM_CATEGORY   TOTAL   SERVICEABLE UNDER_REPAIR    CONDEMNED
----------------------------------------------------------------
chair           5       1           2               2
table           5       3           1               1

关于sql - 同一列上的不同值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297185/

相关文章:

sql - 如何在同一查询的另一个字段中使用计算字段

sql - join条件和where条件的区别

database - PL/SQL 在整个数据库中搜索一个字符串

mysql - 如何在 MySQL 中返回数据透视表输出?

sql - PostgreSQL 中一致的域/类型别名行为

mysql - SQL:数据被分成多行

Oracle 查找基于函数的索引的依赖列

.net - Oracle ODP.NET 版本不可知的替代方案

具有非计数的Mysql数据透视表

sql - 具有多种数据类型的动态数据透视表