How to get the first and last row for an id, based on timestamp on big query
- User
How to get the first and last row for an id, based on timestamp on big query
- Assistant
To get the first and last row for an id based on timestamp in BigQuery, you can use a combination of window functions and subqueries. Here's an example query that demonstrates how to achieve this:
WITH ranked_data AS ( SELECT id, timestamp, ROW_NUMBER() OVER (PARTITION BY id ORDER BY timestamp) AS row_num_asc, ROW_NUMBER() OVER (PARTITION BY id ORDER BY timestamp DESC) AS row_num_desc FROM your_table ) SELECT id, timestamp AS first_timestamp, last_timestamp FROM ( SELECT id, timestamp, MAX(CASE WHEN row_num_asc = 1 THEN timestamp END) OVER (PARTITION BY id) AS first_timestamp, MAX(CASE WHEN row_num_desc = 1 THEN timestamp END) OVER (PARTITION BY id) AS last_timestamp FROM ranked_data ) WHERE first_timestamp IS NOT NULL
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.