简体   繁体   English

如何在子查询中按 sql 数据分组以显示进化

[英]how to group by sql data in a sub-query to show evolution

I have my sqlite database which contains urls and the number of times it has been visited per week.我有我的 sqlite 数据库,其中包含 url 和每周访问的次数。 it's stored this way:它是这样存储的:

uid, url, date, nb_visits,...

I would like to get every single URL with the evolution of the number of visits grouped by date.我想通过按日期分组的访问次数的演变来获取每一个 URL。 something that could looks like:看起来像这样的东西:

 "my_url_1","45,54,76,36,78"

here my assumption is that there are 5 dates stored into the db, don't need the dates, just want them to be ordered from old to recent I tried something like this, but don't accept 2 field in the second select这里我的假设是有 5 个日期存储到数据库中,不需要日期,只是希望它们从旧到最近排序

select url, visits,
(select sum(visits) from data d2 where d2.url=d1.url group by date) as evol
from data d1
where date = (select max(date) from data);

This query isn't working just wanted to share what i'm trying to do Thanks for the help此查询不起作用只是想分享我正在尝试做的事情感谢您的帮助

What you want is the result of GROUP_CONCAT() for each url.您想要的是每个 url 的GROUP_CONCAT()的结果。
The problem with the aggregate function GROUP_CONCAT() is that it does not support an ORDER BY clause, which you need to sort the visits by date, so the result that you would get is not guaranteed to be correct.聚合 function GROUP_CONCAT()的问题是它不支持ORDER BY子句,您需要按日期对访问进行排序,因此不能保证您得到的结果是正确的。

In SQLite there is also a GROUP_CONCAT() window function which supports an ORDER BY clause and can be used to return the result that you want:在 SQLite 中还有一个GROUP_CONCAT() window function 支持ORDER BY子句,可用于返回您想要的结果:

SELECT DISTINCT url,
       GROUP_CONCAT(visits) OVER (
         PARTITION BY url 
         ORDER BY date
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
       ) visits
FROM data 

See a simplified demo .查看简化的演示

Are you looking for group_concat() ?您在寻找group_concat()吗?

select url, group_concat(visits)
from (select d.*
      from data d
      order by url, date
     ) d
group by url;

Note: SQLite doesn't support an order by as part of the group_concat() syntax.注意:SQLite 不支持将order by作为group_concat()语法的一部分。 In theory, sorting in the subquery should have the desired effect of ordering the dates.理论上,子查询中的排序应该具有对日期进行排序的预期效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM