Mysql 多个条件下的聚合值
根据下表Mysql 多个条件下的聚合值,mysql,sql,Mysql,Sql,根据下表 +-----------+-------------+----------+ | tours | tour_user | tag_tour | +-----------+-------------+----------+ | id | tour_id | tag_id | | startdate | user_id | tour_id | +-----------+-------------+----------+ 我希望实现如下结果集
+-----------+-------------+----------+
| tours | tour_user | tag_tour |
+-----------+-------------+----------+
| id | tour_id | tag_id |
| startdate | user_id | tour_id |
+-----------+-------------+----------+
我希望实现如下结果集:
+-----------------+----------------+----------------+
| DATE(startdate) | COUNT(user_id) | COUNT(tour_id) |
+-----------------+----------------+----------------+
| 2017-12-01 | 55 | 32 |
+-----------------+----------------+----------------+
用文字描述参与一次旅行的用户数量和旅行数量应按天数汇总
此外,旅游和用户参与的计数应可通过标签过滤,标签通过tag_tour table many to may关系附在旅游上。
例如,我只需要附加tag_id 1和2的旅游和旅游用户计数
目前我支持以下查询:
SELECT DATE(tours.start) AS acum_date,
COUNT(tour_user.user_id) AS guide_assignments,
A.tour_count
FROM `tour_user`
LEFT JOIN `tours` ON `tours`.`id` = `tour_user`.`tour_id`
LEFT JOIN
(SELECT DATE(tours.start) AS tour_date,
COUNT(DISTINCT tours.id) AS tour_count
FROM tours
GROUP BY DATE(tours.start)) AS A ON `A`.`tour_date` = DATE(tours.start)
GROUP BY `acum_date`
ORDER BY `acum_date` ASC
问题是,只返回巡更/用户总数,而不返回过滤后的总数。基本查询是:
select t.startdate, count(tu.user_id) as num_users, count(distinct t.id) as num_tours
from tours t left join
tour_user tu
on tu.tour_id = t.id
group by t.startdate;
在这种情况下,我建议使用exists来过滤标记:
select t.startdate, count(tu.user_id) as num_users, count(distinct t.id) as num_tours
from tours t left join
tour_user tu
on tu.tour_id = t.id
where exists (select 1 from tour_tags tt where tt.tour_id = t.tid and tt.tag_id = <tag1>) and
exists (select 1 from tour_tags tt where tt.tour_id = t.tid and tt.tag_id = <tag2>)
group by t.startdate;
添加一些样本数据和匹配的预期结果。你已经尝试了什么,你在哪里卡住了?我附上了我的当前状态,非常感谢你!工作起来很有魅力:-