在多个条件下聚合值

时间:2017-12-04 20:14:21

标签: mysql sql

鉴于以下表格

to

我想要实现这样的结果集:

+-----------+-------------+----------+
|   tours   |  tour_user  | tag_tour |
+-----------+-------------+----------+
| id        | tour_id     | tag_id   |
| startdate | user_id     | tour_id  |
+-----------+-------------+----------+

用文字描述参与游览的用户数量和游览量应该按天汇总。

另外,游览和用户参与的数量应该通过tag_tour表(多对五关系)附加到游览的标签过滤。 例如。我只想要使用tag_id 1和2附加的游览和用户数。

目前我使用此查询:

+-----------------+----------------+----------------+
| DATE(startdate) | COUNT(user_id) | COUNT(tour_id) |
+-----------------+----------------+----------------+
| 2017-12-01      |             55 |             32 |
+-----------------+----------------+----------------+

这样做的问题是,只返回了总的游览/用户数,而不是过滤后的数量。

1 个答案:

答案 0 :(得分:1)

基本查询是:

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;
相关问题