I have the following query to get the value of a particular column : level1 at the starting time and ending time. I'm currently using subqueries to perform this, but would like to just complete it with a single SELECT query.
SELECT
id,
(SELECT
b1.level1
FROM
table b1
WHERE
b1.id = b.id
and b1.start_time = MIN(b.start_time)) AS level1_at_start,
(SELECT
b1.level1
FROM
table b1
WHERE
b1.id = b.id
and b1.end_time = MAX(b.end_time)) AS level1_at_end
FROM
table b
GROUP BY b.id
;
SQL Fiddle link : link
Sample input and output :
id level1 start_time end_time
-------------------------------------
i1 10 2 7
i1 50 5 10
i2 60 6 11
i2 20 1 6
i3 30 3 8
i3 40 4 9
id level1_at_start level1_at_end
----------------------------------------
i1 10 50
i2 20 60
i3 30 40
scalar subqueries. Try to avoid them; they complicate your code.