取每天的最大值并总结mysql

时间:2014-12-08 23:12:21

标签: php mysql sql

我有一个包含3列的表格(server varchar(20)transactions int(20)timestamp timestamp(0))。有多个服务器记录他们在一天中遇到的事务。我想编写一个查询,在多个月的过程中对最大事务(每天)进行求和,并显示每个月的列。

我相信我接近以下破解的查询,但问题是它需要整个月的最大值,而不是获得当月每天最大值的总和。

SELECT IFNULL(server, 'TOTAL') AS Server,
       FORMAT(SUM(MAX(CASE WHEN DATE(TIMESTAMP) >= DATE('2014-10-01')
                  AND DATE(TIMESTAMP) < DATE('2014-11-01') THEN transactions ELSE 0 END),0)) AS 'Oct - 2014',
       FORMAT(SUM(MAX(CASE WHEN DATE(TIMESTAMP) >= DATE('2014-11-01')
                  AND DATE(TIMESTAMP) < DATE('2014-12-01') THEN transactions ELSE 0 END),0)) AS 'Nov - 2014',
       FORMAT(SUM(MAX(CASE WHEN DATE(TIMESTAMP) >= DATE('2014-12-01')
                  AND DATE(TIMESTAMP) < DATE('2015-01-01') THEN transactions ELSE 0 END),0)) AS 'Dec - 2014',
       '' AS 'Total'
FROM transactionstable
GROUP BY Server WITH ROLLUP;

1 个答案:

答案 0 :(得分:0)

您希望嵌套的group by,首先按日期和服务器获取最大值,然后由服务器获取sum()。查询草图是:

select server, sum(maxt)
from (select date(timestamp) as d, server, max(transactions) as maxt
      from transactiontable tt
      where date(timestamp) between @TIMESTAMP1 and @TIMESTAMP2
      group by date(timestamp), server
     ) t
group by server;

编辑:

只需在外部查询中进行条件聚合:

select server, sum(maxt),
       sum(case when year(timestamp) = 2014 and month(timestamp) = 11 then maxt end) as sum_201411,
       sum(case when year(timestamp) = 2014 and month(timestamp) = 12 then maxt end) as sum_201412,
       sum(case when year(timestamp) = 2015 and month(timestamp) = 1 then maxt end) as sum_201501
from (select date(timestamp) as d, server, max(transactions) as maxt
      from transactiontable tt
      where date(timestamp) between @TIMESTAMP1 and @TIMESTAMP2
      group by date(timestamp), server
     ) t
group by server;