TSQL - 按纬度和经度以及平均速度分组

时间:2017-06-13 07:22:07

标签: sql-server tsql group-by average

我有这个SQL查询

SELECT 
    [machine], 
    [speed], 
    Round([latitude], 3)  AS Latitude, 
    Round([longitude], 3) AS Longitude 
FROM
    [position] WITH (nolock) 
WHERE  
    (attime BETWEEN '20170606 8:00' AND '20170606 20:00' ) 
    AND machine IN (SELECT DISTINCT [machine] 
                    FROM [haul] WITH (nolock) 
                    WHERE ([timestart] BETWEEN '20170606 8:00' AND '20170606 20:00') 
                      AND machine IN (72)) 
    AND [speed] > 0

它返回一个数据集,如:

ID    SPEED   LAT     LON
-----------------------------
72 - 3,6  - 14,368 - 26,898
72 - 14,4 - 14,368 - 26,898
72 - 28,8 - 14,368 - 26,898
72 - 32,4 - 14,368 - 26,897

但我需要获得平均速度和坐标,以便查看以下记录:

ID    SPEED   LAT     LON
---------------------------
72 - 15,6 - 14,368 - 26,898   
72 - 32,4 - 14,368 - 26,897

当我尝试此查询时:

SELECT 
    [machine], 
    Avg([speed]) AS Speed, 
    Avg(Round([latitude], 3)) AS Latitude, 
    Avg(Round([longitude], 3)) AS Longitude 
FROM   
    [wdata_position] WITH (nolock) 
WHERE
    (attime BETWEEN '20170606 8:00' AND '20170606 20:00') 
    AND machine IN (SELECT DISTINCT [machine] 
                    FROM [wdata_haul] WITH (nolock) 
                    WHERE ([timestart] BETWEEN '20170606 8:00' AND '20170606 20:00') 
                      AND machine IN (72)) 
    AND [speed] > 0 
GROUP BY 
    [machine], [speed], latitude,  longitude 

它将行数从3,926减少到3,883,我看到了这个数据集:

72  3,59999990463257    14,357  26,898
72  3,59999990463257    14,359  26,901
72  3,59999990463257    14,359  26,901
72  3,59999990463257    14,366  26,899
72  3,59999990463257    14,368  26,899
72  3,59999990463257    14,368  26,898
72  3,59999990463257    14,368  26,898
72  3,59999990463257    14,368  26,898
72  3,59999990463257    14,368  26,9

这根本不是我需要的。

如何更改SQL以实现目标?

谢谢!

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解您正在查看的数据(例如,当纬度/经度坐标保持不变时,机器72的速度如何变化?),但我想我明白了无论如何你要做什么。

听起来你想要获得平均速度"对于机器,纬度和经度的每个独特组合?

如果是这样,那么您只需要修改您的查询以按这些列分组,以便仅聚合速度(使用平均值):

SELECT [machine], 
       Avg([speed])          AS Speed, 
       Round([latitude], 3)  AS Latitude, 
       Round([longitude], 3) AS Longitude 
FROM   [wdata_position] WITH (nolock) 
WHERE  ( attime BETWEEN '20170606 8:00' AND '20170606 20:00' ) 
       AND machine IN (SELECT DISTINCT [machine] 
                       FROM   [wdata_haul] WITH (nolock) 
                       WHERE  ( [timestart] BETWEEN '20170606 8:00' AND 
                                                    '20170606 20:00' ) 
                              AND machine IN ( 72 )) 
       AND [speed] > 0 
GROUP  BY 
       [machine], 
       Round([latitude], 3), 
       Round([longitude], 3)