2

我有一个非常简单的表格:

Date, kWh

它有大约 4 年的数据。

如何生成如下结果集:

Year, Result
2010, 123211
2011, 123213
2012, 123211
2013, xxxxxx

其中 xxxx 是对该年度的预测。

该预测将结合 2013 年迄今为止的日期总和,加上平均千瓦时乘以 2013 年剩余的天数。

4

3 回答 3

1

This will calculate projected use correctly with leap years. As you can see, the leap year calculation takes more logic than the rest. Since the projection comes closer as the year progresses, then the whole year has passed, "Projected" shows actual use.

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.

To make the average count over multiple years, the query needs to be modified a little;

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])

This uses a cte to calculate the average to use it later in the query.

Another SQLfiddle.

于 2013-03-13T06:57:02.243 回答
0

你应该做两个查询。第一个是按 YEAR 的简单分组,第二个是关于去年、剩余天数、平均 kWh 的一行信息查询。然后突出 LEFT JOIN 这些表,你会得到你想要的。

SQLFiddle 演示

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;
于 2013-03-13T08:34:38.460 回答
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])

于 2013-03-13T06:28:16.167 回答