【问题标题】:mysql group by with repeated value and countmysql group by 重复值和计数
【发布时间】:2016-11-20 08:43:21
【问题描述】:

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

我的查询是:

选择 s.id,s.user_id,s.start_date,s.end_date,count(s.user_id) as num_of_subscriptions 从 订阅 s 加入用户 u (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

【问题讨论】:

    标签: mysql group-by


    【解决方案1】:

    我认为您需要一个子查询而不是 group by so 给定

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-20
      • 2018-05-18
      • 2018-06-29
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多