dpdhf02040 2014-12-03 09:07
浏览 41
已采纳

Mysql计数并拆分为DAY,WEEK,YEAR为同一查询中的统计信息

I want to get statistics for something.

I'm trying to get count for today, this week, this month.

My query:

"SELECT COUNT(id) FROM images i WHERE i.user_id = 3 GROUP BY DAY(i.created_at), WEEK(i.created_at), MONTH(i.created_at)"

Output:

array(7) {
  [0]=>
  array(1) {
    ["COUNT(id)"]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    ["COUNT(id)"]=>
    string(1) "1"
  }
  [2]=>
  array(1) {
    ["COUNT(id)"]=>
    string(1) "5"
  }
  [3]=>
  array(1) {
    ["COUNT(id)"]=>
    string(1) "5"
  }
  [4]=>
  array(1) {
    ["COUNT(id)"]=>
    string(1) "7"
  }
  [5]=>
  array(1) {
    ["COUNT(id)"]=>
    string(2) "17"
  }
  [6]=>
  array(1) {
    ["COUNT(id)"]=>
    string(1) "1"
  }
}

But i want to split like:

day = 5,
week = 15,
month = 67

But how?


Complete Working Query:

SELECT
                COUNT(i.id) AS `all`,
                (
                    SELECT
                        COUNT(id)
                    FROM
                        images
                    WHERE
                        user_id = i.user_id AND WEEK(created_at) = WEEK(NOW())
                )
                AS `week`,
                (
                    SELECT
                        COUNT(id)
                    FROM
                        images
                    WHERE
                        user_id = i.user_id AND MONTH(created_at) = MONTH(NOW())
                )
                AS `month`,
                (
                    SELECT
                        COUNT(id)
                    FROM
                        images
                    WHERE
                        user_id = i.user_id  AND DAY(created_at) = DAY(NOW())
                )
                AS `day`
            FROM
                images i
            WHERE
                i.user_id = " . $user->getId()
  • 写回答

1条回答 默认 最新

  • doqs8936 2014-12-03 10:16
    关注

    If I understood you right this should be what you're looking for

    SELECT Count(*)                         AS day, 
           (SELECT Count(*) 
            FROM   images 
            WHERE  user_id = i.user_id 
                   AND Week(i.created_at) = Week(Now()) 
            GROUP  BY Week(i.created_at))  AS week, 
           (SELECT Count(*) 
            FROM   images 
            WHERE  user_id = i.user_id 
                   AND Month(i.created_at) = Month(Now()) 
            GROUP  BY Month(i.created_at)) AS month 
    FROM   images i 
    WHERE  i.user_id = 3 
           AND Day(i.created_at) = Day(Now()) 
    GROUP  BY Day(i.created_at) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程