用(my)sql计算每个日期的差异

时间:2017-09-11 13:27:55

标签: mysql sql aggregation

我有一个(mysql)表,如下所示:

|date      |status
|2017-07-10|done
|2017-07-10|new 
|2017-07-11|done
|2017-07-11|done 
|2017-07-12|done
|2017-07-12|done 
|2017-07-12|new 

现在我希望状态完成(或所有状态)的每个日期的计数差异所以在2017-07-11我得到一个,因为还有一个状态比前一天更多,依此类推

|date      |cnt
|2017-07-11|1
|2017-07-12|0

我已经有一个SQL,它给出了一个输入日期的结果:

SELECT '2017-07-11' as d2,
       (SELECT count(*) as cnt 
          FROM table 
         WHERE status = 'done' 
           AND date > DATE_ADD(d2, INTERVAL 1 DAY) 
           AND date < DATE_ADD(d2, INTERVAL 2 DAY)) - 
       (SELECT count(*) as cnt 
          FROM table 
         WHERE status = 'done' 
           AND date > d2 
           AND date < DATE_ADD(d2, INTERVAL 1 DAY)) as cnt;

但这只适用于d2的静态日期,而不是子查询。有人可以帮忙吗?如果可能的话,我也会为postgres采取解决方案。

1 个答案:

答案 0 :(得分:1)

SELECT cur.dt,
       nxt.cnt - cur.cnt
  FROM (SELECT dt,
               COUNT(stat) cnt
          FROM tab
         WHERE stat = 'done'
         GROUP BY dt
       ) nxt
  JOIN 
       (SELECT (dt + 1) dt,
               COUNT(stat) cnt
          FROM tab
         WHERE stat = 'done'
         GROUP BY dt
       ) cur
    ON nxt.dt = cur.dt

结果

dt        nxt.cnt - cur.cnt
20170711  1
20170712  0