Mysql:选择每月总发生次数

时间:2015-06-11 09:22:52

标签: mysql dql

在MySQL中,我得到了一个类似于:

的表
id  user_id date
1   1       2014-09-27
2   1       2014-11-05
3   1       2014-11-14
4   2       2014-12-03
5   1       2014-12-23

我想选择每月总人数。

预期产量:4

2014-09 = 1 user
2014-10 = 0 user
2014-11 = 1 user //user 1 is present twice in november, but I want him only once per month
2014-12 = 2 user

total expected = 4

到目前为止,我的要求是:

SELECT count(id) 
FROM myTable u1 
WHERE EXISTS(
    SELECT id 
    FROM myTable u2 
    WHERE u2.user_id = u1.user_id
    AND DATE_SUB(u2.date, INTERVAL 1 MONTH) > u1.date
);

输出正确的数量,但在我(不那么重)的表上,执行需要数小时。任何提示使这一个更轻或更快?

奖金:

由于INTERVAL 1 MONTH在DQL中不可用,是否可以通过Doctrine QueryBuilder进行此操作?

3 个答案:

答案 0 :(得分:1)

试试这个!

它应该能满足你的需要......

        SELECT
          EXTRACT(YEAR FROM dates) AS the_year,
          EXTRACT(MONTH FROM dates) AS the_month,
          COUNT( DISTINCT user_id ) AS total
        FROM 
          myTable
        GROUP BY
          EXTRACT(YEAR FROM dates),
          EXTRACT(MONTH FROM dates);

答案 1 :(得分:1)

对于你的问题,我会做的是:

  • 创建按月分组不同总和的子订单
  • 创建一个产生子结果总和的请求。

这是a working example (with your datas) sqlFiddle

这是请求:

SELECT SUM(nb_people)
FROM (
-- This request return the number of distinct people in one month.
SELECT count(distinct(user_id)) AS nb_people, MONTH(`date`), YEAR(`date`)
FROM test
GROUP BY MONTH(`date`)
) AS subQuery
;

答案 2 :(得分:0)

SELECT COUNT(DISTINCT user_id), YEAR(date) + '-' + MONTH(date)
FROM MyTable
GROUP BY YEAR(date), MONTH(date)