Eric Auld :
I'm working on a problem on Leetcode about SQL. The problem gives a table called Weather
, with entries for Id
(as in, id of a temperature measurement), Temperature
, and RecordDate
. Each Id
comes from a subsequent day. They ask for the Id
s where the temperature that day exceeded the temperature the previous day.
My attempt was
select id
from
(select id, temperature, lag(temperature, 1) over (ORDER BY RecordDate) prevs
from weather)
where temperature > prevs
but it tells me there's a syntax error near the (ORDER BY...
part.
What's wrong?
Yogesh Sharma :
Your query syntactical incorrect :
First, if you use LAG()
with position parameter then you must specify the third parameter too. However, by default it is 1. So, don't need to specify :
LAG(temperature) over (ORDER BY RecordDate) AS prevs_temp
Second, your sub-query doesn't have alias :
select t.id
from (select id, temperature, LAG(temperature) over (ORDER BY RecordDate) AS prevs_temp
from weather
) t -- alias missing
where (t.temperature > t.prevs_temp or t.prevs_temp is null); -- will return id which doesn't have previous `temperature`.