Mysql 引用嵌套查询的派生表
我昨天发布了与此类似的内容,但现在我想要与我的查询稍有不同的内容 -
我正在尝试查询数据库以检索一段时间内访问过某个网站的一次性用户的数量。数据看起来像这样:
Day | UserID
1 | A
1 | B
2 | B
3 | A
4 | B
4 | C
5 | D
我希望查询结果看起来像这样
Time Span | COUNT(DISTINCT UserID)
Day 1 to Day 1 | 2
Day 1 to Day 2 | 1
Day 1 to Day 3 | 0
Day 1 to Day 4 | 1
Day 1 to Day 5 | 2
结果是 2,1,0,1,2 因为,在这些天结束时,有 X 个用户拥有访问过一次。例如,对于第 5 天,在第 5 天结束时,用户 c 和 d 仅访问过一次。
我想我正在寻找与此类似的查询:
select d.day, (select count(distinct userid) from visits where day<=d.day)
from (select distinct day from visits) d
上面的查询与我的查询之间的差异寻找的是我希望这个新查询只考虑每个时间跨度的一次性用户,而不是重复用户。
谢谢
I posted something similar to this yesterday, but now I'd like something a little different from my query-
I'm trying to query a database to retrieve the number of one-time users who have visited a website over time. The data looks something like this:
Day | UserID
1 | A
1 | B
2 | B
3 | A
4 | B
4 | C
5 | D
I'd like the query result to look this this
Time Span | COUNT(DISTINCT UserID)
Day 1 to Day 1 | 2
Day 1 to Day 2 | 1
Day 1 to Day 3 | 0
Day 1 to Day 4 | 1
Day 1 to Day 5 | 2
The result is 2,1,0,1,2 because, at the end of those days, there are X number of users who have visited a single time. e.g. for day 5, at the end of day 5, users c and d have visited only once each.
I think I'm looking for a query similar to this:
select d.day, (select count(distinct userid) from visits where day<=d.day)
from (select distinct day from visits) d
The difference between the query above and what I'm looking for is that I'd like this new query to consider only one-time users for each time span, and not repeat users.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该子查询应该适用于明确的要求。
原文
您一定是从 SQL Server 中汲取了这个想法 - 它是唯一允许您引用两次删除(嵌套)查询的 RDBMS (IIRC)。请指出您想要什么,我们可以重写查询。
对于显示的确切查询,您不需要 2 级子查询
This subquery should work for the clarified requirements.
Original
You must have taken the idea from SQL Server - it is the only RDBMS (IIRC) that will allow you to reference a twice removed (nesting) query. Please indicate what you want and we can rewrite the query.
For the exact query shown, you don't need 2 levels of subquery