如何在SQL中正确使用AVG()?

时间:2018-11-08 01:36:23

标签: sql sql-server syntax

我通过在此表中存储SSI值来跟踪RF网络中的基站性能:

TABLE BASE_SSI:
    wayside     BIGINT (PK)
    timestamp   datetime
    base        varchar(12)
    ssi         int

SSI每小时读取一次,并存储在此表中,并具有大约一年的读数。

通过此查询,我可以提取过去任意一天的一天的SSI值:

select wayside,timestamp,base,ssi from BASE_SSI 
where wayside=225520220000 
and timestamp > DATEADD(day,-7,getdate())
and timestamp < DATEADD(day,-6,getdate())
order by timestamp desc

这给了我这些结果:

wayside         timestamp             base        ssi
225520220000    2018-11-02 00:21:09   423.3.01    33
225520220000    2018-11-01 22:31:03   423.3.01    32
225520220000    2018-11-01 20:40:53   423.3.01    32
225520220000    2018-11-01 18:50:45   423.3.01    31
225520220000    2018-11-01 17:00:35   423.3.01    33
225520220000    2018-11-01 15:10:26   423.3.01    34
225520220000    2018-11-01 13:20:20   423.3.01    38
225520220000    2018-11-01 11:30:11   423.3.01    37
225520220000    2018-11-01 09:40:03   423.3.01    35
225520220000    2018-11-01 07:49:03   423.3.01    35
225520220000    2018-11-01 05:59:50   423.3.01    34
225520220000    2018-11-01 04:09:43   423.3.01    34
225520220000    2018-11-01 02:19:34   423.3.01    34

我需要的是一个查询,该查询向我提供过去24小时内所有路段的AVERAGE ssi。结果应该是:

wayside         date         base        avg_ssi
225520220000    2018-11-01   423.3.01    34
225520230000    2018-11-01   423.2.21    21
225520240000    2018-11-01   423.4.11    18
225520250000    2018-11-01   423.1.21    55
225520260000    2018-11-01   422.2.01    62
225520270000    2018-11-01   452.3.07    33
225520280000    2018-11-01   425.1.03    25

我只需要整数ssi的平均值即可,如图所示。

我尝试在SELECT语句中使用AVG(ssi),但是我不确定如何在选定的时间段内将其应用于所有路边值。例如,在原始查询中, 我在SELECT行中添加了“ AVG(ssi)作为avg_ssi”,但它只为每条记录生成了“平均” SSI,与SSI值相同。

此查询的伪SQL版本是“显示给定日期每个路边的24小时平均SSI”。

1 个答案:

答案 0 :(得分:1)

您可以尝试在avg上将group byCONVERT(char(10), timestamp,126)结合使用,让日期时间以yyyy-MM-dd的格式group by每个日期。

select wayside,CONVERT(char(10), timestamp,126),base,avg(ssi) as avg_ssi
from BASE_SSI 
where timestamp > DATEADD(day,-7,getdate()) and timestamp < DATEADD(day,-6,getdate())
group by CONVERT(char(10), timestamp,126),base,wayside
order by timestamp desc

编辑

根据您的评论,您可以尝试使用ROW_NUMBER窗口函数来获取每个ssi的第一个base

SELECT wayside,
       CONVERT(char(10), timestamp,126),
       base,
       ssi as avg_ssi 
FROM (
    select wayside,timestamp,base,ssi,Row_number() over(partition by base order by timestamp) rn
    from BASE_SSI 
    where timestamp > DATEADD(day,-7,getdate()) and timestamp < DATEADD(day,-6,getdate())
) t1
where rn = 1
order by timestamp desc