HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Select lowest ID and calculate deviation from the lowest

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thedeviationlowestcalculateandselectfrom

Problem

I'm trying to create a view. I have some data in my SQL Server database, and I want to order them by their mark1 and mark2. Now when I sort them I want to select the mark1 who has the lowest mark2 and calculate what's the deviation from other mark1s.
The table is looking right now like this, but without deviation.

|   mark1    |    mark2    |      mass    ||    deviation |
|:-----------|------------:|:------------:||:------------:|
| 0001       |      10000  |     10,0     ||    min0001   |
| 0001       |      15000  |     12,0     ||    +20%      |
| 0002       |      11200  |     18,0     ||    min0002   |
| 0002       |      13000  |     35,5     ||    +97.2%    |
| 0002       |      14565  |     85,5     ||    375%      |
| 0003       |      15004  |     15,4     ||    min0003   |
| 0003       |      21250  |     17,4     ||    +12.9%    |
| 0003       |      60764  |     16,4     ||    6.49%     |


And now, as you see it's ordered by mark1 and mark2.
Now, my problem is the deviation column, I need it to take mark1, Let's say 0001 (his mark2 is 10000) and find the lowest mass and find the deviation from other 0001 (15000). As you can see the in the table.

Solution

FIRST_VALUE (Transact-SQL)


Returns the first value in an ordered set of values in SQL Server
2014.

Partition on mark1 and order by mark2.

Something like this should do it for you:

select T.*,
       100 * (T.mass - T.FirstMass) / T.FirstMass as Deviation
from (
     select T.*,
            first_value(T.mass) over(partition by T.mark1 order by T.mark2) as FirstMass
     from dbo.YourTable as T    
     ) as T;


SQL Fiddle

Code Snippets

select T.*,
       100 * (T.mass - T.FirstMass) / T.FirstMass as Deviation
from (
     select T.*,
            first_value(T.mass) over(partition by T.mark1 order by T.mark2) as FirstMass
     from dbo.YourTable as T    
     ) as T;

Context

StackExchange Database Administrators Q#101614, answer score: 8

Revisions (0)

No revisions yet.