交叉引用最近日期数据

cross reference nearest date data

我有三个tableElecUser,ElecUsage,ElecEmissionFactor
ElecUser: UserID UserName 1 Main Building 2 Staff Quarter

ElecUsage: UserID Time Amount 1 1/7/2010 23230 1 8/10/2011 34340 1 8/1/2011 34300 1 2/3/2012 43430 1 4/2/2013 43560 1 3/2/2014 44540 2 3/6/2014 44000

ElecEmissionFactor: Time CO2Emission 1/1/2010 0.5 1/1/2011 0.55 1/1/2012 0.56 1/1/2013 0.57

预期结果:
UserName Time CO2 1 2010 11615 1 2011 37752 (34340*0.55 + 34300*0.55) 1 2012 24320.8 1 2013 24829.2 1 2014 25387.8 2 2014 25080

逻辑是 ElecUsage.Amount * ElecEmissionFactor。 如果是同一用户,同一年份,则将它们相加作为当年的记录。 我的查询是:
SELECT ElecUser.UserName, Year([ElecUsage].[Time]), SUM((ElecEmissionFactor.CO2Emission*ElecUsage.Amount)) As CO2 FROM ElecEmissionFactor, ElecUser INNER JOIN ElecUsage ON ElecUser.UserID = ElecUsage.UserID WHERE (((Year([ElecUsage].[Time]))>=Year([ElecEmissionFactor].[Time]))) GROUP BY ElecUser.UserName, Year([ElecUsage].[Time]) HAVING Year([ElecUsage].[Time]) = Max(Year(ElecEmissionFactor.Time));

但是,这只显示有排放因子的年份。
挑战是将没有排放因子的年份参考最近有排放因子的年份。
子查询可能是解决方案之一,但我没有这样做。
我卡住了一段时间。希望看到你的回复。
谢谢

试试这样的..

-- 未测试

select T1.id, year(T1.time) as Time, sum(T1.amount*T2.co2emission) as CO2 
from ElecUsage T1 
left outer join ElecEmissionFactor T2 on (year(T1.time) = year(T2.time))
Group by year(T1.time), T1.id

这样使用子查询得到对应的因子

    select T1.id, 
        year(T1.time) as Time, 
        sum(T1.amount*
                    (
                    select top 1 CO2Emission from ElecEmissionFactor T2 
                    where year(T2.time) <= year(T1.time) order by T2.time desc
                    )
        ) as CO2 
from ElecUsage T1 
Group by year(T1.time), T1.id