I am having trouble querying some data. The table I am trying to pull the data from is a LOG table, where I would like to see changes in the values next to each other (example below)
Table:
+-----------+----+-------------+----------+------------+ | UNIQUE_ID | ID | NAME | CITY | DATE | +-----------+----+-------------+----------+------------+ | xa220 | 1 | John Smith | Berlin | 2020.05.01 | | xa195 | 1 | John Smith | Berlin | 2020.03.01 | | xa111 | 1 | John Smith | München | 2020.01.01 | | xa106 | 2 | James Brown | Atlanta | 2018.04.04 | | xa100 | 2 | James Brown | Boston | 2017.12.10 | | xa76 | 3 | Emily Wolf | Shanghai | 2016.11.03 | | xa20 | 3 | Emily Wolf | Shanghai | 2016.07.03 | | xa15 | 3 | Emily Wolf | Tokyo | 2014.02.22 | | xa12 | 3 | Emily Wolf | null | 2014.02.22 | +-----------+----+-------------+----------+------------+
Desired outcome:
+----+-------------+----------+---------------+ | ID | NAME | CITY | PREVIOUS_CITY | +----+-------------+----------+---------------+ | 1 | John Smith | Berlin | München | | 2 | James Brown | Atlanta | Boston | | 3 | Emily Wolf | Shanghai | Tokyo | | 3 | Emily Wolf | Tokyo | null | +----+-------------+----------+---------------+
I have been trying to use FIRST and LAST values, however, cannot get the desired outcome.
select distinct id, name, city, first_value(city) over (partition by id order by city) as previous_city from test
Any help is appreciated! Thank you!