按行计算平均值sql

时间:2018-10-02 22:35:39

标签: sql sql-server

我有一个这种类型的表:

place                  time            id

 1. place 1 ----------------0-----------------------1
 2. place 1 ----------------141---------------------2
 3. place 1-----------------280---------------------3
 4. place 2-----------------0----------------------- 1
 5. place 2-----------------136---------------------2
 6. place 2-----------------260---------------------3

我想计算每个位置的平均时间,以使结果列看起来像这样:

place                  time            id   avgTime

 1. place 1 ----------------0-----------------------1------140.333
 2. place 1 ----------------141---------------------2------140.333
 3. place 1-----------------280---------------------3------140.333
 4. place 2-----------------0-----------------------1------132
 5. place 2-----------------136---------------------2------132
 6. place 2-----------------260---------------------3------132

4 个答案:

答案 0 :(得分:1)

使用窗口功能!

select t.*, avg(time * 1.0) over (partition by place) as place_avg
from t;

答案 1 :(得分:0)

您可以使用此查询

SELECT id, place, time, (SELECT AVG(time) from places WHERE places.place = pls.place GROUP BY place) as avgTime FROM `places` as pls

答案 2 :(得分:0)

这应该做你的事

SELECT *, AVG(1.0*time) OVER(PARTITION BY place) 
FROM yourTable

您可以在这里进行测试

declare @table as  table (place varchar(100), time int, id int )

insert into @table (place, time, id)
values
('Place1', 0, 1),
('Place1', 141, 2),
('Place1', 280, 3),
('Place2', 0, 1),
('Place2', 136, 2),
('Place2', 260, 3)

select *, avg(1.0*time) over(partition by place) 
from @table

答案 3 :(得分:-1)

请尝试

    select A.PLACE,
           A.TIME,
           A.ID,
          (select avg(TIME) from AVERAGE where PLACE =A.PLACE) avgTIME
    from AVERAGE A
    order by PLACE,ID
相关问题