加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

mysql单列拼接,groupby多个字段使用场景

(2019-01-24 14:47:03)
分类: mysql
假设表字段为
时间                               用户id  阅读文章id
2019-01-20 00:00:01            A
2019-01-20 00:00:02            A
2019-01-20 00:00:03            A
2019-01-20 00:00:01    2          A
2019-01-20 00:00:01    2          C
2019-01-20 00:00:01    1          C
2019-01-21 00:00:01            A
2019-01-21 00:00:02            A
2019-01-21 00:00:01    2          A
2019-01-21 00:00:01    2          C
2019-01-21 00:00:01    1          C
2019-01-22 00:00:01    1          A
2019-01-22 00:00:01    2          A
2019-01-22 00:00:01    1          C

以下语句表示用户3天都读了n篇或以上相同的文章,contentids为相同的文章id用逗号连接(单列连接),group by两个字段是为了排重,表示某用户读了某篇文章:
select
count(a.contentid) repeat_news,GROUP_CONCAT(a.contentid) contentids,a.userid
from
(
select userid,contentid from p_user_income_record where time between "2019-01-20 00:00:00" and "2019-01-20 23:59:59" group by userid,contentid
) a
inner join (
select userid,contentid from p_user_income_record where time between "2019-01-21 00:00:00" and "2019-01-21 23:59:59" group by userid,contentid
) b
on a.userid=b.userid and a.contentid=b.contentid
inner join (
select userid,contentid from p_user_income_record where time between "2019-01-22 00:00:00" and "2019-01-22 23:59:59" group by userid,contentid
) c
on a.userid=c.userid and a.contentid=c.contentid
group by a.userid having repeat_news>=n

当n=1时结果为
repeat_news contentids userid
                  A,C             1
                  A                2
当n=2时结果为
repeat_news contentids userid
                  A,C             1

0

阅读 收藏 喜欢 打印举报/Report
后一篇:截取ip前3段
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有