[英]Getting sql records between two dates from another table
I am currently trying to wrap my head around some SQL I am trying to build.我目前正在尝试围绕我正在尝试构建的一些 SQL 进行思考。 What I have are two tables that appear as so:我有两张表,如下所示:
Audit Table
id | user | action | date
---+------+--------+--------------------
1 | dave | LOGIN | 2020-01-01 00:00:00
2 | dave | VIEW | 2020-01-01 00:01:00
3 | dave | LOGIN | 2020-01-02 00:00:00
etc..
and和
Page Analytics Table
id | user | page | access date
-----------------------------------------
1 | dave | home | 2020-01-01 00:00:30
2 | dave | account | 2020-01-01 00:00:45
3 | dave | about | 2020-01-02 00:00:30
I am trying to capture the number of times per user, per day that that user has logged in, and then accessed a specific page.我试图捕获每个用户每天登录然后访问特定页面的次数。
I am not expecting a particular elegent solution, but there may be something I am missing.我并不期待一个特别优雅的解决方案,但我可能会遗漏一些东西。 I am figuring I am best building up a temporary table containing something like (gathered from the audit table):我想我最好建立一个包含类似(从审计表中收集)的临时表:
id | user | login_start | login_end
-----------------------------------------------------
1 | dave | 2020-01-01 00:00:00 | 2020-01-02 00:00:00
2 | dave | 2020-01-02 00:00:00 | 2020-01-02 00:00:30
And then using this table, join with the page analytics, and counting the visits between these days, and then checking this count is above 0.然后使用这个表,加入页面分析,统计这几天之间的访问量,然后检查这个计数是否在 0 以上。
I am just trying to wrap my head around getting this intermediate table created.我只是想全神贯注地创建这个中间表。 Am I going down the wrong path here?我在这里走错路了吗? Are there better solutions?有更好的解决方案吗?
Thanks in advance..提前致谢..
You can get page counts from your analytics table quite simply like this:您可以像这样简单地从分析表中获取页数:
SELECT DATE(`access date`) `access date`,
page,
user,
COUNT(*) hits
FROM analytics
GROUP BY DATE(`access date`), page, user
If you want also to include logins in your summary you can use UNION ALL to do this.如果您还想在摘要中包含登录信息,您可以使用 UNION ALL 来执行此操作。 ( https://www.db-fiddle.com/f/64yHcewC1KjxfyejjqdaZv/2 ) ( https://www.db-fiddle.com/f/64yHcewC1KjxfyejjqdaZv/2 )
SELECT * FROM (
SELECT DATE(`access date`) date,
CONCAT('viewed ', page) event,
user,
COUNT(*) hits
FROM analytics
GROUP BY DATE(`access date`), page, user
UNION ALL
SELECT DATE(date) date,
'logged in' event,
user,
COUNT(*) hits
FROM audit
WHERE action = 'LOGIN'
GROUP BY DATE(date), user
) summary
ORDER BY date, user, event
Result:结果:
| date | event | user | hits |
| ---------- | -------------- | ---- | ---- |
| 2020-01-01 | logged in | dave | 1 |
| 2020-01-01 | viewed account | dave | 1 |
| 2020-01-01 | viewed home | dave | 1 |
| 2020-01-02 | logged in | dave | 1 |
| 2020-01-02 | viewed about | dave | 1 |
I'm guessing about your logged-in / logged-out requirement though.不过,我猜测您的登录/注销要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.