Query 10 SQL Scripts
Query 10 SQL Scripts
-- Finding n consecutive records where temperature is below zero. And table has a
primary key.
--Table Structure:
drop table if exists weather cascade;
create table if not exists weather
(
id int primary key,
city varchar(50) not null,
temperature int not null,
day date not null
);
-- solution:
with
t1 as
(select *, id - row_number() over (order by id) as diff
from weather w
where w.temperature < 0),
t2 as
(select *,
count(*) over (partition by diff order by diff) as cnt
from t1)
select id, city, temperature, day
from t2
where t2.cnt = 3;
-- Query 10b
-- Finding n consecutive records where temperature is below zero. And table does
not have primary key.
with
w as
(select *, row_number() over () as id
from vw_weather),
t1 as
(select *, id - row_number() over (order by id) as diff
from w
where w.temperature < 0),
t2 as
(select *,
count(*) over (partition by diff order by diff) as cnt
from t1)
select city, temperature, id
from t2
where t2.cnt = 5;
-- Query 10c
-- Finding n consecutive records with consecutive date value.
--Table Structure:
drop table if exists orders cascade;
create table if not exists orders
(
order_id varchar(20) primary key,
order_date date not null
);
-- Solution
with
t1 as
(select *, row_number() over(order by order_date) as rn,
order_date - cast(row_number() over(order by order_date)::numeric as
int) as diff
from orders),
t2 as
(select *, count(1) over (partition by diff) as cnt
from t1)
select order_id, order_date
from t2
where cnt >= 3;