【问题标题】:can we modify this query?我们可以修改这个查询吗?
【发布时间】:2021-11-10 21:32:51
【问题描述】:

我不想让它看起来很复杂。有没有其他方法可以使用简单的关键字来编写这段代码(如果它很长就可以了)?

表格代码:

CREATE TABLE job_data
(
    ds DATE,
    job_id INT NOT NULL,
    actor_id INT NOT NULL,
    event VARCHAR(15) NOT NULL,
    language VARCHAR(15) NOT NULL,
    time_spent INT NOT NULL,
    org CHAR(2)
);

INSERT INTO job_data (ds, job_id, actor_id, event, language, time_spent, org)
VALUES ('2020-11-30', 21, 1001, 'skip', 'English', 15, 'A'),
    ('2020-11-30', 22, 1006, 'transfer', 'Arabic', 25, 'B'),
    ('2020-11-29', 23, 1003, 'decision', 'Persian', 20, 'C'),
    ('2020-11-28', 23, 1005,'transfer', 'Persian', 22, 'D'),
    ('2020-11-28', 25, 1002, 'decision', 'Hindi', 11, 'B'),
    ('2020-11-27', 11, 1007, 'decision', 'French', 104, 'D'),
    ('2020-11-26', 23, 1004, 'skip', 'Persian', 56, 'A'),
    ('2020-11-25', 20, 1003, 'transfer', 'Italian', 45, 'C');

我想修改下面的代码。

WITH cte AS 
(
    SELECT ds, COUNT(job_id) AS no_of_jobs, SUM(time_spent) AS time_taken
    FROM job_data
    WHERE event in ('transfer', 'decision')
    AND ds BETWEEN '2020-11-01' AND '2020-11-30'
    GROUP BY ds
)
SELECT ds, SUM(no_of_jobs) 
OVER ( order  by ds range between unbounded preceding and current row)/sum(time_taken) 
over (order by ds range between unbounded preceding and current row) as throughput_7d 
from cte;

【问题讨论】:

  • 一般来说,窗口函数的替代方案更复杂。创建窗口函数是为了简化这样的查询。
  • @barmar 我想故意使用这些。如果您能在这方面帮助我,我们将不胜感激。
  • 那我不明白这个问题。这已经很简单了。
  • 就像我不想使用 with 子句,我们可以使用子查询来做到这一点

标签: mysql window-functions


【解决方案1】:

用子查询替换cte

SELECT ds, SUM(no_of_jobs) 
    OVER ( order  by ds range between unbounded preceding and current row)/sum(time_taken) 
    over (order by ds range between unbounded preceding and current row) as throughput_7d 
FROM (
    SELECT ds, COUNT(job_id) AS no_of_jobs, SUM(time_spent) AS time_taken
    FROM job_data
    WHERE event in ('transfer', 'decision')
    AND ds BETWEEN '2020-11-01' AND '2020-11-30'
    GROUP BY ds
) AS cte

如果您需要在主查询中多次引用cte,它很有用,如果您只使用一次,则不需要它。

【讨论】:

  • 非常感谢 :)
  • 你应该解释一下,这与原始查询相同,它没有任何优点
  • 我认为这很明显——他只是要求同等但更简单的东西。
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 2013-06-23
相关资源
最近更新 更多