mysql 一个查询里可以做两次 group by 吗

clipboard.png

问题如上,我的想法是需要group by城市一次,然后还需要group by 用户一次,请问正确的应该怎么写?

阅读 9.2k
3 个回答

拆成两条语句

每个城市7天下过单的用户数

select city_id, count(distinct user_id) from order
where create_time > '2019-05-20'
group by city_id;

每个城市中, 首单时间在七天内的用户, 首单时间就是每个用户最小的create_time

这个语句有点复杂, 我还没想到什么简单明了的办法

select st.city_id, count(1) from (
    select city_id, user_id from order
    where min(create_time) > '2019-05-20'
    group by city_id, user_id
)st group by st.city_id;

里面的是先查出首单在七天内的用户, , 然后外层再进行统计

你可以使用两个select集合,然后用union链接起来。

伪代码:
select city_id, count_distinct(order_id) from table_name where create_time > '2019-05-20' group by city_id,user_id

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题