通过两个时间戳从多个表中获取数据

如何解决通过两个时间戳从多个表中获取数据

PostgreSQL 10.12

我有一张表格,其中包含按日期和小时分组的计算数据,例如:

hourly_stats
clicks_count | visitors_count | product_id | promoter_id | bundle_id | date_time
------------------------------------------------------------------------------------------
     15      |        6       |     123    |     456     |    789    | 2018-11-02 12:00:00
     8       |        3       |     123    |     456     |    789    | 2018-11-02 16:00:00
     2       |        1       |     123    |     456     |    789    | 2018-11-13 10:00:00
     5       |        2       |     123    |     456     |    789    | 2018-11-13 21:00:00

每隔一个小时,我都会收集前一个小时的统计信息并将其插入表格中。

此外,为了始终显示最新数据,我使用实例化视图,该视图存储从当前小时的开始到当前时刻(每5分钟刷新一次)的计算数据。

查询的核心部分始终基于两个时间戳值,如下所示:

SELECT *
FROM (
    SELECT
        clicks_count,visitors_count,product_id,promoter_id,bundle_id,date_time
    FROM hourly_stats
    UNION ALL (
        SELECT
            clicks_count,date_time
        FROM materialized_stats
    )
)
WHERE (date_time > start_date AND date_time <= end_date)

此核心部分用于多个非常复杂的查询,这些查询太慢。例如,如果表在其中一种情况下具有超过2000万条记录,则需要花费超过1.5分钟才能完成查询(如果没有行用start_dateend_date进行过滤)。


我决定再添加两个表,其中包含按年-月-日分组的计算数据:

daily_stats
clicks_count | visitors_count | product_id | promoter_id | bundle_id | date_time
------------------------------------------------------------------------------------------
     23      |        9       |     123    |     456     |    789    | 2018-11-02
     7       |        3       |     123    |     456     |    789    | 2018-11-13

以及按年份-月份:

monthly_stats
clicks_count | visitors_count | product_id | promoter_id | bundle_id | date_time
------------------------------------------------------------------------------------------
     30      |       12       |     123    |     456     |    789    | 2018-11

因此,如果我有start_date = '2019-01-01 00:00:00'end_date = '2020-08-12 16:00:00',我将能够收集这样的数据

(SELECT
    clicks_count,date_time
FROM monthly_stats
WHERE 'monthly_condition')
UNION ALL
(SELECT
    clicks_count,date_time
FROM daily_stats
WHERE 'daily_condition')
UNION ALL
(SELECT
    clicks_count,date_time
FROM hourly_stats
WHERE 'hourly_condition')
UNION ALL (
SELECT
    clicks_count,date_time
FROM materialized_stats
)

每个计算行仅在基本时间段(月,日或小时)结束后才添加到相应的表中。因此,对于特定的product_id | promoter_id | bundle_id集,我应该得到:

    来自monthly_stats + 的
  • 19行 来自daily_stats +
  • 11行 来自hourly_stats +
  • 16行
  • materialized_stats中的1行

(在应用程序层上)已经实施的限制:

  1. max end_date的值可能等于当天的结束时间
  2. start_date始终小于end_date
  3. start_dateend_date的值以小时为单位指定

问题:如何在上面实现这些“ monthly_condition”,“ daily_condition”和“ hourly_condition”?它们应该基于start_dateend_date部分,但是我完全不知道该怎么做。

感谢您的帮助。

解决方法

这是一个有趣的问题。对于SQL Server,我不得不解决一次。 PostgreSQL使它变得更加容易。到fullness cte为止的所有内容均已测试。由于我没有您的表格或数据,因此allstats cte是最好的猜测。

with invars as (
  select '2016-08-15 12:35:00'::timestamptz as start_date,'2020-08-12 19:00:00'::timestamptz as end_date
),days as (
  select c.dhour,tstzrange(
           date_trunc('hour',i.start_date),date_trunc('hour',i.end_date),'[)') as qrange
    from invars i
   cross join lateral generate_series(
                date_trunc('hour',interval '1 hour'
              ) as c(dhour)
),calendar as (
  select dhour,date_trunc('day',dhour) as dday,date_trunc('month',dhour) as dmonth,qrange
    from days
),fullness as (
  select dhour,dday,dmonth,qrange,qrange @> tstzrange(dday,dday + interval '1 day','[)') as full_day,qrange @> tstzrange(dmonth,dmonth + interval '1 month','[)') as full_month
    from calendar
),allstats as (
  select clicks_count,visitors_count,product_id,promoter_id,bundle_id
    from monthly_stats
   where date_time in (select distinct to_char(dmonth,'YYYY-MM') 
                         from fullness where full_month)
  union all
  select clicks_count,bundle_id
    from daily_stats
   where date_time in (select distinct to_char(dday,'YYYY-MM-DD') 
                         from fullness where full_day and not full_month)
  union all
  select clicks_count,bundle_id
    from hourly_stats
   where date_time in (select dhour from fullness 
                        where not full_day and not full_month 
                          and dhour < date_trunc(hour,now()))
  union all
  select clicks_count,bundle_id
    from materialized_stats
)
select * from allstats;

我认为您的问题描述遗漏了start_date可以在一个月甚至一天的中间开始的事实。该查询涵盖了这一点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-