计算Oracle表中的行数

时间:2015-12-27 21:44:43

标签: sql oracle oracle11g

我需要按类型计算Oracle表中的行:

CREATE TABLE EVENTS(
  EVENTID INTEGER NOT NULL,
  SOURCE VARCHAR2(50 ),
  TYPE VARCHAR2(50 ),
  EVENT_DATE DATE,
  DESCRIPTION VARCHAR2(100 )
)
/

我需要4种类型的事件 - 严重,信息,警告和错误

如何使用一个SQL查询执行此操作?

最终结果应该是这样的一行结果:

All | Critical | Info | Warning | Error
-------------------------------------------
23  |   2      |  13  |    2    |   3

2 个答案:

答案 0 :(得分:2)

SELECT
    COUNT(*) "All",
    COUNT(CASE WHEN TYPE = 'Critical' THEN 1 END) "Critical",
    COUNT(CASE WHEN TYPE = 'Info' THEN 1 END) "Info",
    COUNT(CASE WHEN TYPE = 'Warning' THEN 1 END) "Warning",
    COUNT(CASE WHEN TYPE = 'Error' THEN 1 END) "Error"
FROM
    EVENTS;

答案 1 :(得分:1)

或使用pivot

SELECT * FROM
(
  SELECT type, count(*) over() "All"
  FROM events
)
PIVOT
(

  COUNT(type)
  FOR type IN ('Critical', 'Info', 'Warning', 'Error')
)