簡體   English   中英

mysql group by具有重復的值和計數

[英]mysql group by with repeated value and count

我有一個分組查詢,但我想用count重復值,例如,我的結果是這樣的:

我的查詢是:

從訂閱中選擇s.id,s.user_id,s.start_date,s.end_date,count(s.user_id)作為num_of_subscriptions個加入用戶u(s.user_id = u.id)GROUP BY s.user_id;

id user_id開始日期結束日期訂閱數

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

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

我想要這樣的數據

id user_id開始日期結束日期訂閱數

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

我認為您需要一個子查詢而不是一個這樣的組

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM