Skip to content
Advertisement

how to select first and last row in 1 query after Filtering and then carry out calculation between the values of two values in one query

I’m using T-SQL 2014

Suppose I have a stock price chart as follow enter image description here

I want to write efficient code for a stored function to display the Open price at the start, Close price at the end, and the difference between Close and Open. Is it possible to do that in one query? The query seems easy but it turned out extremely difficult. My first problem is to display the first row and last row in one query.

My attempt is like this

I feel this code is very clumsy. And it also won’t let me pass, because the ‘Open’and ‘Close’ is not defined yet.

Is there anyway to query this in one select?

Thank you

Advertisement

Answer

We can handle this via a regular query using ROW_NUMBER:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement