我有一个非常简单的表:
Date, kWh
它有大约4年的数据。
如何生成如下结果集:
Year, Result
2010, 123211
2011, 123213
2012, 123211
2013, xxxxxx
其中xxxx是当年的预测。
预测将结合到目前为止2013年的日期总和,加上平均每千瓦时乘以2013年的剩余天数。
答案 0 :(得分:1)
这将使用闰年正确计算预计使用量。如您所见,闰年计算比其他计算更具逻辑性。由于随着年份的进展投影越来越近,整年过去了,“预计”显示了实际使用情况。
SELECT DATEPART(YEAR, [Date]) year, SUM(kWh) *
(365 + ISDATE(CAST(DATEPART(YEAR, [DATE]) AS char(4)) + '0229')) /
COUNT(kWh) Projected
FROM readings
GROUP BY DATEPART(YEAR, [Date])
A simple SQLfiddle to test with
要使平均计数超过多年,需要稍微修改一下查询;
WITH average AS (SELECT AVG(kWh) kWh FROM readings)
SELECT DATEPART(YEAR, a.[Date]) year, SUM(a.kWh) + AVG(b.kWh) *
((365 + ISDATE(CAST(DATEPART(YEAR, a.[DATE]) AS char(4)) + '0229')) -
COUNT(a.kWh)) Projected
FROM readings a, average b
GROUP BY DATEPART(YEAR, a.[Date])
这使用cte来计算稍后在查询中使用它的平均值。
答案 1 :(得分:0)
假设每年都有365天,当然不是真的......
select Datepart(YEAR,[Date]) as [Year],
case when Datepart(YEAR,[Date]) = Datepart(YEAR, getdate())
then 365*Avg(Kwh)
else SUM(Kwh) end as TotalKwh
from table_1
group by Datepart(YEAR,[Date])
答案 2 :(得分:0)
Yous应该进行两次查询。第一个是YEAR的简单组,第二个是关于去年,剩余天数,平均kWh的一行信息查询。然后juts LEFT JOIN这些表格,你会得到你想要的。
with t1 as
(
select
DATEPART(YEAR,[Date]) as Year,
sum(kWh) SumKWH
from t
group by
DATEPART(YEAR,[Date])
),
t2 as
(
select max(DATEPART(YEAR,[Date])) as MaxYear,
AVG(kWH) as AverageKWH,
DATEDIFF(DAY,max([Date]),
CAST( CAST(max(DATEPART(YEAR,[Date])) as varchar(4))+'-12-31' as datetime)
) DaysLeft
from t
)
select t1.YEAR,
t1.SumKWH+ISNULL(AVERAGEKWH*DAYSLEFT,0)
from t1
left join t2 on (t1.Year=t2.MaxYear)
order by t1.YEAR;