MySQL按第一个表的日期分组并计数与第二个表不同的字段

时间:2018-10-17 04:03:23

标签: mysql

我有users个桌子

id | email           | website
1    test@gmail.com     google.com
2    blah@hotmail.com   google.com
3    fred@outlook.com   yahoo.com
4    jeff@gmail.com     yahoo.com

还有一个groups

id | group     | user_id | created
1    group1       1         2018-06-06
2    group2       2         2018-06-06
3    group3       3         2018-09-09
4    group4       4         2018-06-06

我需要每website天计算一次每个created的计数,因此以上内容会给我 google.com 2 2018-06-06

website   | count   | date

google.com    2        2018-06-06
yahoo.com     1        2018-06-06
yahoo.com     1        2018-09-09

我将返回的行按日期分组,但是使用以下查询,每行的计数均为1

select count(distinct users.website), groups.created 
from user_groups as groups
 join users on users.id = groups.user_id
 group by groups.created

所以我很简单

count(distinct users.website)  |   created
 1                                  2018-06-06
 1                                  2018-06-06
 1                                  2018-06-06
 1                                  2018-09-09

2 个答案:

答案 0 :(得分:1)

尝试以下

DEMO

select website,created,count(website) as cnt
from groups t2 join users t1 on t1.id = t2.userid
group by website, created

答案 1 :(得分:0)

尝试

Select distinct(groups.created),count(distinct(users.website))
from user_groups as groups
join users on users.id = groups.user_id
group by groups.created

应该工作。