Home > Enterprise >  can we modify this query?
can we modify this query?

Time:09-16

I don't want it to look much complicated. Is there any other way to write this code by using simple keywords (will be fine if it get long)?

code for table:

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');

I want below code to get modified.

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;

CodePudding user response:

Replace cte with the subquery.

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

A cte is useful if you need to refer to it multiple times in the main query, you don't need it if you're just using it once.

  • Related