日期组中的MySQL多个计数

时间:2015-07-05 13:49:11

标签: mysql

try
{
    MailMessage msg = new MailMessage();
    msg.From = new MailAddress("myemail@gmail.com);
    msg.To.Add(new MailAddress("theiremil@email.com));
    msg.Subject = "This is the subject";
    msg.Body = "This is the body";
    SmtpClient sc = new SmtpClient("smtp.gmail.com", 465);
    sc.EnableSsl = true;
    sc.UseDefaultCredentials = false;
    sc.Credentials = new NetworkCredential("myemail@gmail.com", "pass");
    sc.DeliveryMethod = SmtpDeliveryMethod.Network;
    sc.Send(msg);
    erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
    erroremail.Text = "ERROR: " + ex.Message;
}

我有这个查询,它为传出调用的每个小时日期分组计数。有没有办法在同一个查询中同时获得传入的数量?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
 Calldate
 from_unixtime(FLOOR(UNIX_TIMESTAMP(calldate)/(60*60))*(60*60)) GroupTime, 
 SUM(calltype='incoming') as CntIn, 
 SUM(calltype='outgoing') as CntOut 
FROM asterisk.cdr 
WHERE accountcode = '10102-131' 
  AND DATE (calldate) = DATE (NOW()) 
  AND calltype IN ('incoming', 'outgoing' )
GROUP BY GroupTime;

Sample SQL Fiddle

答案 1 :(得分:1)

假设“传出”和“传入”是通话中的描述符:

SELECT date(calldate), hour(calldate) as callhour,
       count(*) as Cnt,
       sum(calltype = 'outgoing') as CntOut,
       sum(calltype = 'incoming') as CntIn
FROM asterisk.cdr 
WHERE accountcode = '10102-131' AND
      (calldate >= curdate() and calldate < date_sub(curdate(), interval 1 day)
      ) AND
      calltype IN ('outgoing' , 'incoming')
GROUP BY date(calldate), hour(calldate);

注意:

  • 我发现hour()函数更容易用来获取小时。但是,它返回一个整数而不是一个时间,所以它可能不是你真正想要的。
  • date()上使用calldate可以阻止使用索引。所以,我用不等式替换了那个逻辑。
  • 我假设你想要传出和来电的单独计数。

答案 2 :(得分:0)

如果可以通过calltype分组,请尝试:

SELECT 
   calltype 
   , calldate
   , from_unixtime(FLOOR(UNIX_TIMESTAMP(calldate)/(60*60))*(60*60)) GroupTime
   ,case when calltype='outgoing' then COUNT(*) else 0 end as CntOut 
   ,case when calltype='ingoing' then COUNT(*) else 0 end as CntIn 
 FROM asterisk.cdr 
 WHERE 
   accountcode = '10102-131' 
   AND DATE (calldate) = DATE (NOW()) 
   AND (calltype = 'outgoing' or calltype='ingoing')--if calltype in only 'ingoing' or 'outgoing', you can omit this line
 GROUP BY calltype, calldate;

但如果没有,查询会有点复杂:

SELECT 
   t.calldate
   , from_unixtime(FLOOR(UNIX_TIMESTAMP(t.calldate)/(60*60))*(60*60)) GroupTime
   , t_out.cnt as CntOut
   , t_in.cnt as CntIn
 FROM 
  asterisk.cdr as t
  left join (select calldate,count(*) cnt from asterisk.cdr where calltype='outgoing' group by calldate) as t_out
  on t.calldate=t_out.calldate
  left join (select calldate,count(*) cnt from asterisk.cdr where calltype='ingoing' group by calldate) as t_in
  on t.calldate=t_in.calldate
 WHERE 
   t.accountcode = '10102-131' 
   AND DATE (t.calldate) = DATE (NOW()) 
 GROUP BY  t.calldate;