mysql group by with重复值和计数

时间:2016-11-20 08:43:22

标签: mysql group-by

我有一个group by的查询,但我想用count重复值,例如,我的结果是这样的:

我的查询是:

选择 s.id,s.user_id,s.start_date,s.end_date,count(s.user_id)as num_of_subscriptions 从 订阅加入用户你(s.user_id = u.id) GROUP BY s.user_id;

id user_id start_date end_date number_of_subscription

1 2 2016-05-20 2016-05-21 4

2 5 2016-05-20 2016-05-21 3

我想获得这样的数据

id user_id start_date end_date number_of_subscription

1 2 2016-05-20 2016-05-21 4

1 2 2016-05-10 2016-05-21 4

1 2 2016-05-11 2016-05-21 4

1 2 2016-05-12 2016-05-21 4

2 5 2016-05-20 2016-05-21 3

2 5 2016-05-20 2016-05-21 3

2 5 2016-05-20 2016-05-21 3

1 个答案:

答案 0 :(得分:1)

我认为你需要一个子查询而不是一个组 给出

drop table if exists t;
create table t
(user_id int,start_date date,end_date date);
insert into t values
( 2 ,'2016-05-20' ,'2016-05-21'),
( 2 ,'2016-05-10' ,'2016-05-21'),
( 2 ,'2016-05-11' ,'2016-05-21'),
( 2 ,'2016-05-12' ,'2016-05-21'),
( 5 ,'2016-05-20' ,'2016-05-21'),
( 5 ,'2016-05-20' ,'2016-05-21'),
( 5 ,'2016-05-20' ,'2016-05-21');

select user_id,start_date,end_date, (select count(*) from t t1 where t1.user_id = t.user_id)
from t t

结果

+---------+------------+------------+----------------------------------------------------------+
| user_id | start_date | end_date   | (select count(*) from t t1 where t1.user_id = t.user_id) |

    +---------+------------+------------+----------------------------------------------------------+
    |       2 | 2016-05-20 | 2016-05-21 |                                                        4 |
    |       2 | 2016-05-10 | 2016-05-21 |                                                        4 |
    |       2 | 2016-05-11 | 2016-05-21 |                                                        4 |
    |       2 | 2016-05-12 | 2016-05-21 |                                                        4 |
    |       5 | 2016-05-20 | 2016-05-21 |                                                        3 |
    |       5 | 2016-05-20 | 2016-05-21 |                                                        3 |
    |       5 | 2016-05-20 | 2016-05-21 |                                                        3 |
    +---------+------------+------------+----------------------------------------------------------+
    7 rows in set (0.00 sec)