Oracle按日期和数字查询条形图

时间:2015-09-03 20:09:26

标签: sql oracle oracle11g oracle10g

我有这个表用于存储4种类型的消息:信息,警告,警报和错误。

upper_red

我需要在过去15天的条形图中按类型和日期显示事件,例如:enter image description here

你可以帮我解决这个Oracle查询吗?

查询的输出示例:

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

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select event_date,
       sum(case when type = 'Error' then 1 else 0 end) as Error,
       sum(case when type = 'Warn' then 1 else 0 end) as Warn,
       sum(case when type = 'Info' then 1 else 0 end) as Info
from events e
where event_date >= trunc(sysdate) - 15
group by event_date
order by event_date;

警告:如果名为event_date的字段实际上有时间组件,那么您应该在trunc(event_date)select中使用group by

答案 1 :(得分:0)

变式A:逐行 你想要的数字(= COUNT(*))例如特定event_date中特定源的错误(= TYPE)事件。因此,三元组(source,type,event_date)构建一个组,并且您想知道该组中有多少事件。

Select source, type, event_date, count(*) 
from events 
group by source, type, event_date;

这样结果就是

event_date  source  type   count
11-12-2015  server  error  12
11-12-2015  server  info   22
11-12-2015  server  warn   11
12-12-2015  server  error  32
12-12-2015  server  info   12
12-12-2015  server  warn   14

变体B:并排

Select event_date, source, sum(error), sum(info), sum(warn)
From (select event_date, source, 
decode(Type, 'error', 1, 0) as error,
decode(Type, 'info', 1, 0) as info,
decode(Type, 'warn', 1, 0) as warn
From events)
Group by event_date, source;

你应该得到:

event_date  source  error  warn  info
11-12-2015  server   12    22    11
12-12-2015  server   32    12    14

decode是某种if-then-else。

可选:仅限15天 正如你问的那样。

简单地向(内部)选择添加where子句,如where event_date >= sysdate - 15

Select source, type, event_date, count(*) 
from events 
where event_date >= sysdate - 15
group by source, type, event_date;

或b)

Select event_date, source, sum(error), sum(info), sum(warn)
From (select event_date, source, 
decode(Type, 'error', 1, 0) as error,
decode(Type, 'info', 1, 0) as info,
decode(Type, 'warn', 1, 0) as warn
From events
where event_date >= sysdate - 15)
Group by event_date, source;