请帮助我解决与SUM,AVG,MTD SUM相关的问题,关于通过设施中的仪表查找油量流量。
说,有两个设施
每天都有流量计。表FACILITY_OIL如下所示 -
TimeStamp----------Facility----------Meter----------OilVolume
10-SEP-2014 | NORTH | N1 | 100
10-SEP-2014 | NORTH | N2 | 200
10-SEP-2014 | SOUTH | S1 | 300
10-SEP-2014 | SOUTH | S2 | 400
10-OCT-2014 | NORTH | N1 | 100
10-OCT-2014 | NORTH | N2 | 200
10-OCT-2014 | SOUTH | S1 | 300
10-OCT-2014 | SOUTH | S2 | 400
11-OCT-2014 | NORTH | N1 | 400
11-OCT-2014 | NORTH | N2 | 300
11-OCT-2014 | SOUTH | S1 | 200
11-OCT-2014 | SOUTH | S2 | 100
12-OCT-2014 | NORTH | N1 | 100
12-OCT-2014 | NORTH | N2 | 200
12-OCT-2014 | SOUTH | S1 | 300
12-OCT-2014 | SOUTH | S2 | 400
我必须找到按设施分组的以下内容:
输出应如下所示12-OCT
Facility-----DailySum-----MTD_Sum-----MTD_Avg-----Prev_Month_Avg
NORTH | 300 | 1300 | 108.33 | 10
SOUTH | 700 | 1700 | 141.66 | 23.33
Here for NORTH on 12-OCT,
DailySum = (N1+N2)
MTD SUM = (N1 + N2) from 01-Oct to 12-Oct
MTD_Avg = MTD_SUM/12days
Pre_Month_Avg = (100+200)/30
是否可以以相同的格式输出。我的局限是我不能使用SP。它必须是一种观点。
我尝试使用group by但无法实现它。任何帮助深表感谢。万分感谢!
感谢您的帮助!
似乎有一天工作完美。我能够使用您的查询。
我添加了#rol;'在最后获得总和。但是,现在需求已更改为获取当天每天的数据集。所以看起来应该如下:
Timestamp--Facility--DailySum--MTD_Sum--MTD_Avg--Prev_Month_Avg
10-Oct | NORTH | 300 | 1300 | 108.33 | 10
10-Oct | SOUTH | 700 | 1700 | 141.66 | 23.33
10-Oct | TOTAL | 1000| 3000 | 249.99 | 33.33
12-Oct | NORTH | 300 | 1300 | 108.33 | 10
12-Oct | SOUTH | 700 | 1700 | 141.66 | 23.33
12-Oct | TOTAL | 1000| 3000 | 249.99 | 33.33
我尝试过你的修改过的查询 -
select case when null then 'TOTAL' else Facility end as 'Facility'
,sum(case when [TimeStamp]>=dateadd(dd,datediff(dd,0,getdate()),0) then OilVolume else 0 end) as DailySum
,sum(case when [TimeStamp]>=dateadd(mm,datediff(mm,0,getdate()),0) then OilVolume else 0 end) as MTD_Sum
,sum(case when [TimeStamp]>=dateadd(mm,datediff(mm,0,getdate()),0) then OilVolume else 0 end)/datepart(dd,getdate()) as MTD_Avg
,sum(case when [TimeStamp]>=dateadd(mm,datediff(mm,0,getdate()),0) then 0 else OilVolume end)/datepart(dd,dateadd(dd,datepart(dd,getdate())*-1,getdate())) as Prev_Month_Avg
from yourtable
where [TimeStamp]>=dateadd(mm,datediff(mm,0,getdate())-1,0)
group by Timestamp, Facility with rollup
它似乎不适用于简单的分组。我不知道如何获得一天的重复结果。我不能使用CURSOR或循环视图。请帮忙。谢谢!
答案 0 :(得分:0)
我会使用案例
select
sum(case when timestamp = '12-OCT-2014' then meter + oilVolume else 0 end),
sum(case when timestamp between '01-OCT-2014' and '12-OCT-2014' then meter + volume else 0 end),
sum(case when timestamp between '01-OCT-2014' and '12-OCT-2014' then meter + volume else 0 end) / datediff("dd",'01-OCT-2014' , '12-OCT-2014'),
sum(case when timestamp between '01-SEP-2014' and '30-SEP-2014' then meter + volume else 0 end ) / datediff("dd",'01-SEP-2014' , '30-SEP-2014')
from ...
您可以使用参数更改日期。