计算每组差异的总和

时间:2017-08-25 11:31:48

标签: sql-server database

我有下表:

Sensor | building | Date_time  | Current_value
1      |   1      | 20.08.2017 |   20
1      |   1      | 21.08.2017 |   25
1      |   1      | 22.08.2017 |   35
2      |   1      | 20.08.2017 |  120
2      |   1      | 21.08.2017 |  200
2      |   1      | 22.08.2017 |  210
3      |   2      | 20.08.2017 |   20
3      |   2      | 21.08.2017 |   25
3      |   2      | 22.08.2017 |   85
5      |   2      | 20.08.2017 |  320
5      |   2      | 21.08.2017 |  400
5      |   2      | 22.08.2017 |  410

假设传感器ID是唯一的,建筑物ID也是如此。

我需要通过从每个传感器的MAX值中减去MIN值来计算每个建筑物在任何给定时间范围内的总值,然后将每个建筑物的总和分组。

在上面的示例中,它将是

Sensor 1: (35 - 20)=15
Sensor 2: (210-120)=90
Building 1 = 15+90 = 105
(...)
Building 2 = 65+90 = 155

非常感谢任何正确方向的指针!

2 个答案:

答案 0 :(得分:2)

您在询问如何计算每个传感器的最小值和最大值之间的差异,然后汇总每个建筑物的差异。

with diffs as (
    SELECT Building,Sensor, MAX(Current_Value)-MIN(Current_Value) as diff
    FROM SomeTable
    GROUP BY Building, Sensor 
)
SELECT Building,sum(diff)
FROM diffs
GROUP BY Building

如果你想限制时间段,你必须在CTE中这样做:

with diffs as (
    SELECT Building,Sensor, MAX(Current_Value)-MIN(Current_Value) as diff
    FROM SomeTable
    WHERE Date_Time between @start and @end
    GROUP BY Building, Sensor 
)
SELECT Building,sum(diff)
FROM diffs
GROUP BY Building

您可以将此查询转换为可在其他查询中使用的用户定义函数:

create function fn_TotalDiffs(@start datetime2(0), @end datetime2(0))
returns table 
as 
Return (
    with diffs as (
        select Building,Sensor, MAX(Current_Value)-MIN(Current_Value) as diff
        from SomeTable
        Group by Building, Sensor 
    )
    select Building,sum(diff) as Total
    from diffs
    Group by Building
)

答案 1 :(得分:2)

使用窗口函数min / max over()

的另一个选项

示例

Select Building
      ,Total  = sum(R1)
 From (
        Select Distinct
               Building
              ,R1 = max([Current_value]) over (Partition By Building,Sensor) 
                   -min([Current_value]) over (Partition By Building,Sensor) 
         From YourTable
         Where Date_time between @Date1 and @Date2
      ) A      
 Group By Building

<强>返回

Building    Total
1           105
2           155