嵌套分组(SQL),保留分组值

时间:2016-04-08 15:48:23

标签: sql group-by

我的数据结构如下:

date    hour    station     dem     imp
2/1/2016     1  station1    dem1    6
2/1/2016     2  station1    dem1    1
2/1/2016     1  station1    dem2    0
2/1/2016     2  station1    dem2    10
2/2/2016     1  station1    dem1    6
2/2/2016     2  station1    dem1    4
2/2/2016     1  station1    dem2    5
2/2/2016     2  station1    dem2    5
2/1/2016     1  station 2   dem1    8
2/1/2016     2  station 2   dem1    1
2/1/2016     1  station 2   dem2    7
2/1/2016     2  station 2   dem2    1
2/2/2016     1  station 2   dem1    8
2/2/2016     2  station 2   dem1    7
2/2/2016     1  station 2   dem2    9
2/2/2016     2  station 2   dem2    0

我希望它看起来像下面这样:

Imp的计算方法是:每小时的损失总和,然后是每天的平均小时数。

date         station    imp
2/1/2016     station1   8.5
2/1/2016     station2   8.5
2/2/2016     station1   10.0
2/2/2016     station2   12.0

E.g。获得2/1/2016和station1; imp =((6 + 0)+(10 + 1))/ 2

我遇到的问题是,我在GROUP BYdemhour等问题上date时,不确定如何保留电台值。< / p>

1 个答案:

答案 0 :(得分:1)

您可以将总和除以count(distinct dem),其中每个日期/电台对的唯一标识数为

select date, station, sum(imp) / count(distinct dem)
from mytable
group by date, station

http://sqlfiddle.com/#!9/17001/1