Rune FS
Rune FS

Reputation: 21742

Normalizing values in SQL query

I have an data table I wish to perform some numeric analysis on for that I need all the values to be in the same range. 0..1.

I have a somewhat slow and longhanded way of accomplishing this but would like a more straigt forward performant solution to my problem

What I need to do is:

group by projectid with in each project take the average of each of the values and divide by the largest average for the entire set.

currently I have

select avg(foo * 1.0)/ (Select MAX(IL) FROM (select avg(foo * 1.0) as IL from table group by     
                                             ProjectID) tbl)
from table

so if the list is

projectid  | foo
-----------------
1          | 1
1          | 2
2          | 4
2          | 2

the largest average is 3 and the result should therefor be

0.5,1

where the first is the average for projectId 1 divided by 3 and the second is the average for projectId 2 divided by 3

Upvotes: 3

Views: 8375

Answers (2)

roman
roman

Reputation: 117380

SQL FIDDLE EXAMPLE

select
    Projectid,
    avg(cast(foo as decimal(29, 2))) / max(avg(cast(foo as decimal(29, 2)))) over ()
from tbl1
group by Projectid

Upvotes: 5

podiluska
podiluska

Reputation: 51494

;with cte as
(
    select projectid, AVG(foo) av
    from yourtable
    group by projectid
)
    select *,
        av/(select MAX(av) from cte)
    from cte

Upvotes: 1

Related Questions