繁体   English   中英

SQL优化:窗口函数生成的两个计算字段相乘

[英]SQL Optimization: multiplication of two calculated field generated by window functions

给定两个时间序列表tbl1(time, b_value)tbl2(time, u_value)

https://www.db-fiddle.com/f/4qkFJZLkZ3BK2tgN4ycCsj/1

假设我们要求u_value在每一天的最后一个值, b_value当天的累计总和,以及它们的乘积,即daily_u_value * b_value_cum_sum

以下查询计算所需的输出:

WITH cte AS (
SELECT
  t1.time,
  t1.b_value,
  t2.u_value * t1.b_value AS bu_value,
  last_value(t2.u_value) 
  OVER 
  (PARTITION BY DATE_TRUNC('DAY', t1.time) ORDER BY DATE_TRUNC('DAY', t2.time) ) AS daily_u_value
FROM stackoverflow.tbl1 t1
LEFT JOIN stackoverflow.tbl2 t2
ON 
    t1.time = t2.time
)
SELECT
    DATE_TRUNC('DAY', c.time) AS time,
    AVG(c.daily_u_value) AS daily_u_value, 
    SUM( SUM(c.b_value)) OVER (ORDER BY DATE_TRUNC('DAY', c.time) ) as b_value_cum_sum,
    AVG(c.daily_u_value) * SUM( SUM(c.b_value) ) OVER (ORDER BY DATE_TRUNC('DAY', c.time) ) as daily_u_value_mul_b_value
FROM cte c
GROUP BY 1
ORDER BY 1 DESC

我想知道我能做些什么来优化这个查询? 是否有任何替代解决方案可以产生相同的结果?

db 文件演示
从您的查询:执行时间:250.666 毫秒到我的查询执行时间:205.103 毫秒
那里似乎有一些进展。 主要是减少演员的时间,因为我看到你有很多次从时间戳转换到时间戳。 我想知道为什么不只是另一个日期列。


我首先执行我的查询然后执行您的查询,这意味着比较条件相当公平,因为第二次执行通常比第一次更快。


alter table tbl1 add column t1_date date;
alter table tbl2 add column t2_date date;
update tbl1 set t1_date = time::date;
update tbl2 set t2_date = time::date;

WITH cte AS (
SELECT
  t1.t1_date,
  t1.b_value,
  t2.u_value * t1.b_value AS bu_value,
  last_value(t2.u_value)
  OVER
  (PARTITION BY t1_date ORDER BY t2_date ) AS daily_u_value
FROM stackoverflow.tbl1 t1
LEFT JOIN stackoverflow.tbl2 t2
ON
    t1.time = t2.time
)
SELECT
    t1_date,
    AVG(c.daily_u_value) AS daily_u_value,
    SUM( SUM(c.b_value)) OVER (ORDER BY t1_date ) as b_value_cum_sum,
    AVG(c.daily_u_value) * SUM( SUM(c.b_value) ) OVER
        (ORDER BY t1_date ) as daily_u_value_mul_b_value
FROM cte c
GROUP BY 1
ORDER BY 1 DESC

暂无
暂无

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

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