Skip to content
Advertisement

How to determine a percentage gain or loss for a series of people in a table in SQL

I’ve posted a few questions about a system I’m trying to write, and feel bad for asking so many questions. However, I’m still quite new (or revisiting from years ago) to the finer elements of SQL Server, so please forgive and help me!

I have imported data from a JSON into a table, which has a whole host of different information contained within it, one of which being a person’s weight recorded over time. I have the following code to produce this:

What I get from this is (a sample):

I would like then the following output, for the sake of an example, Resident 5:

Ultimately, I’m wanting to be able to say from the first date, or from a date entered via a variable to either the last date or another defined end date variable, what the percentage change has been for each resident in the list. Most residents will have numerous entries, I’ve just tried to give an example of one.

If this was in something like Delphi (old school, I know) then this would be relatively easy. However, for clarity reasons I’m trying to do as much of the processing in SQL Server. Can anyone offer any guidance? I’m aware of using LAG to perhaps find the previous row to use as a compare, but I’m finding it hard to get my head around going through the entire table for EACH resident at a time, and then generating the sort of list above. Or, is it better to just go through the entire table, and running a tally for each person (which would seem to be a much more complicated route).

Thanks Ant

EDIT (20/12)

Thanks to @Zhorov, I am now very close. However, whereas before I did seem to be getting accurate results up to 10 entries before a div/0 came along, I am now getting wild scores and I’m sure it’s because I’ve messed up along the way of implementing your suggestions. The code now is

This gives me the following results:

I’m missing something somewhere! Can anyone spot it for me? I think it’s not resetting for each new resident?

Thanks

Advertisement

Answer

It’s a complicated example, but if I understand you correctly, the next approach, using FIRST_VALUE() and percentage calculations may help here:

Sample data:

Statement:

Results:

Update:

It seems, that your [Weight] column holds numbers as text. Try to convert these values with TRY_CONVERT() (numeric(10, 2) is just a test data type, use an appropriate numeric data type). One possible approach is:

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