如何按月显示树结果?

时间:2014-12-31 16:37:43

标签: mysql

我想在一个查询中计算实现3个结果:

  1. 从当前行计算'app_creationdate'=(' month')的所有结果

  2. 从当前行计算'app_start'=('月')的所有结果

  3. 计算'app_creationsdate'所在的所有结果< 'app_start'和'app_start'=('月')来自当前行

  4. 我的表:

    app_id | app_creationdate(timestamp)| app_start(日期时间) 00001 | 2014-11-17 19:39:04 | 2014-11-18 09:30:00

    SELECT 
        DATE_FORMAT( app_creationsdate, '%m' ) AS 'month', 
        COUNT( app_id ) AS 'new',
        (SELECT COUNT( app_id ) 
         FROM appointments WHERE MONTH(app_start) = MONTH(NOW())) AS 'act',
        (SELECT COUNT( app_id ) 
         FROM appointments WHERE MONTH(app_creationsdate) < MONTH(app_start)) AS 'prev' 
    
    FROM appointments
    WHERE app_owner = 2 AND app_creationsdate > DATE_SUB(now(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT( app_creationsdate, '%Y%m' ) 
    

2 个答案:

答案 0 :(得分:0)

我不完全确定你想要完成什么,但我确实注意到一件事:

DATE_FORMAT(a2.app_start,&#39;%m&#39;)= DATE_FORMAT(&#39;月&#39;,&#39;%m&#39;)

这:DATE_FORMAT(&#39; month&#39;,&#39;%m&#39;)...评估为NULL,因此将其等同于任何东西永远不会起作用(我不认为)无论如何,但我是MySQL的新手...... :))。

答案 1 :(得分:0)

这可能更接近你想要的。我对prev场景仍感到有点困惑,所以我尽了最大努力。我使用EXTRACT(YEAR_MONTH FROM ...)来获取每个日期的年份和月份,以便我们可以进行每月比较。这可能就是你试图对DATE_FORMAT业务做的事情。

SELECT DATE_FORMAT( app_creationsdate, '%m' ) AS 'month', 
   COUNT( app_id ) AS 'new',
   -- get all other appointments that start in this month
   (SELECT COUNT( act.app_id ) 
      FROM appointments AS act 
     WHERE EXTRACT(YEAR_MONTH FROM act.app_start) = EXTRACT(YEAR_MONTH FROM appointments.app_creationsdate)) AS 'act',
   -- get all appointments that were created before they started (???) and that started before this month

   (SELECT COUNT( prev.app_id ) 
      FROM appointments AS prev
     WHERE EXTRACT(YEAR_MONTH FROM prev.app_creationsdate) < EXTRACT(YEAR_MONTH FROM appointments.app_creationsdate)
       AND EXTRACT(YEAR_MONTH FROM prev.app_start) = EXTRACT(YEAR_MONTH FROM appointments.app_creationsdate)) AS 'prev' 
  FROM appointments
 WHERE app_owner = 2
   AND app_creationsdate > DATE_SUB(now(), INTERVAL 12 MONTH)
 GROUP BY EXTRACT(YEAR_MONTH FROM app_creationsdate)