sql查询特定日期之间的月份日期(从日期到日期)

时间:2016-12-16 12:12:24

标签: mysql sql

我在该表上有一个SQL表

event_name  location    meter_id    timestamp       
powerfail    hyd        0000123     '2016-11-23 15:03:57'
powerfail    hyd        00000123    '2016-11-24 14:03:57'
像这样我有桌子我有这么多记录我想要按月记录我有一个查询请尽快修改发送  我的疑问是:

select distinct event_name, count(event_name)
from eventlog el  
where event_name='power_failed' 
and  el.timestamp >= '2016-10-01'  
and  el.timestamp < '2016-10-30' 
group by event_name 
order by event_name desc 

我想要这样的输出

MONTH名称EventName EventCount

3 个答案:

答案 0 :(得分:0)

在派生表中,将时间戳转换为字符串,并选择其前7个字符以获取YYYY-MM部分字符。然后GROUP BY结果:

select el.mnth, el.event_name, count(*)
from
(
    select substr(cast(timestamp as varchar(30)), 1, 7) as mnth, event_name
    from eventlog
) el
group by el.mnth, el.event_name 
order by el.event_name desc, el.mnth

答案 1 :(得分:0)

select  event_name, count(event_name)
from eventlog el  
where event_name='power_failed' 
And  el.timestamp BETWEEN '2016-10-01' And   '2016-10-30' 
group by event_name 
order by event_name desc 

答案 2 :(得分:0)

select 
    monthname(timestamp) as monthname, 
    event_name, (select count(*) from eventlog where event_name =     
    el.event_name and month(timestamp) = month(el.timestamp) and 
    year(timestamp)= year(el.timestamp)) as EventCount
from eventlog el 
where el.timestamp >= '2016-10-01' and el.timestamp < '2016-10-30' 
group by event_name, year(timestamp), month(timestamp)

希望这对你有用。