0% found this document useful (0 votes)
18 views1 page

Query+7+ +script

The document describes fetching weather records from a table when London had temperatures below zero for 3 or more consecutive days. It provides the table structure and sample data inserted. The solution selects records where the temperature and previous 2 days temperatures are below zero to find periods of 3 or more consecutive cold days.

Uploaded by

Denny Lauw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views1 page

Query+7+ +script

The document describes fetching weather records from a table when London had temperatures below zero for 3 or more consecutive days. It provides the table structure and sample data inserted. The solution selects records where the temperature and previous 2 days temperatures are below zero to find periods of 3 or more consecutive cold days.

Uploaded by

Denny Lauw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

-- Query 7:

From the weather table, fetch all the records when London had extremely cold
temperature for 3 consecutive days or more.

Note: Weather is considered to be extremely cold then its temperature is less than
zero.

--Table Structure:

drop table weather;


create table weather
(
id int,
city varchar(50),
temperature int,
day date
);
delete from weather;
insert into weather values
(1, 'London', -1, to_date('2021-01-01','yyyy-mm-dd')),
(2, 'London', -2, to_date('2021-01-02','yyyy-mm-dd')),
(3, 'London', 4, to_date('2021-01-03','yyyy-mm-dd')),
(4, 'London', 1, to_date('2021-01-04','yyyy-mm-dd')),
(5, 'London', -2, to_date('2021-01-05','yyyy-mm-dd')),
(6, 'London', -5, to_date('2021-01-06','yyyy-mm-dd')),
(7, 'London', -7, to_date('2021-01-07','yyyy-mm-dd')),
(8, 'London', 5, to_date('2021-01-08','yyyy-mm-dd'));

select * from weather;

--Solution:

select id, city, temperature, day


from (
select *,
case when temperature < 0
and lead(temperature) over(order by day) < 0
and lead(temperature,2) over(order by day) < 0
then 'Y'
when temperature < 0
and lead(temperature) over(order by day) < 0
and lag(temperature) over(order by day) < 0
then 'Y'
when temperature < 0
and lag(temperature) over(order by day) < 0
and lag(temperature,2) over(order by day) < 0
then 'Y'
end as flag
from weather) x
where x.flag = 'Y';

You might also like