构造SQL查询

时间:2016-02-25 14:52:04

标签: mysql sql

我在数据库中有一个大型日志表,我需要从中提取一些信息。

我努力的输出是:

日 - 尝试 - 尝试失败

我的表看起来像这样;

LogID - Timestamp - Sender - Receiver - SecondsConEst - InOut - ErrorMsg - MsgID

要提取此错误,我需要计算MsgID,其中SecondsConEst是> = 1并且InOut = Out以及MsgID重复8次或更多次的位置。

目前我有:

SELECT date(timestamp) as Day, count(MsgID) as attempts
FROM database.log 
where Receiver like 'AAB%' and out = 'Out' and (SecondsConEst >= '1' and ErrorMsg != '') 
group by MsgID having count(messageid) >= 8 ;

现在这给了我

Day           Attempts
2016-02-15    9
2016-02-15    8

但我想合并这个。如果尝试是8或更多,则可以调用"失败"应该算作失败,显示那天失败的总数。

我尝试过使用

count(case when count(MsgID >= 8) then 1 else NULL end) 

在我的选择中,但这给了我"无效使用群组功能"。

我当然也喜欢显示总尝试次数,是否可以为此进行某种内部联接?喜欢

SELECT (distinct MsgID) inner join where...

任何指针都会很棒。

2 个答案:

答案 0 :(得分:1)

这样的事情:

SELECT Day,count(case when attempts > 8 then 1 end) as cntFailed FROM(
    SELECT date(timestamp) as Day, count(MsgID) as attempts
    FROM database.log 
    where Receiver like 'AAB%' and out = 'Out' and (SecondsConEst >= '1' and ErrorMsg != '') 
    group by MsgID having count(messageid) >= 8 );
GROUP BY Day

如果我理解正确的话,你所缺少的是另一个选择来包装你的选择。

答案 1 :(得分:1)

我认为你需要另一个级别的聚合:

SELECT day, SUM(attempts >= 8) as Failures, COUNT(*) as Total
FROM (SELECT date(MIN(timestamp)) as Day, count(MsgID) as attempts
      FROM database.log 
      WHERE Receiver like 'AAB%' and out = 'Out' and
            (SecondsConEst >= '1' and ErrorMsg <> '') 
      GROUP BY MsgID
     ) 
GROUP BY day;

请注意,此版本明确选择每个邮件ID的最小时间戳。这将处理邮件在多天之间拆分的情况。