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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题