dotn30471 2014-12-08 23:12
浏览 280
已采纳

取每天的最大值并总结mysql

I have a table with 3 columns (server varchar(20), transactions int(20), timestamp timestamp(0)). There are multiple servers that log the transactions they get hit with over the course of a day. I want to write a query that sums the max transaction (per day) over the course of a multiple months and display a column for each month.

I believe I am close with the following broken query, but the problem is that it takes the max value of the whole month rather than getting the sum of the max of each day in the month.

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条回答 默认 最新

  • douxigai8757 2014-12-08 23:20
    关注

    You want nested group bys, first by date and server to get the maximum and then by server to get the sum(). A sketch of the query is:

    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;
    

    EDIT:

    Just do a conditional aggregation in the outer query:

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器