如何根据T-SQL中前几个月的数据确定缺失月份的值

我在特定时间点发生了一系列交易:
CREATE TABLE Transactions (
    TransactionDate Date NOT NULL,TransactionValue Integer NOT NULL
)

数据可能是:

INSERT INTO Transactions (TransactionDate,TransactionValue)
VALUES ('1/1/2009',1)
INSERT INTO Transactions (TransactionDate,TransactionValue)
VALUES ('3/1/2009',2)
INSERT INTO Transactions (TransactionDate,TransactionValue)
VALUES ('6/1/2009',3)

假设TransactionValue设置了某种级别,我需要知道事务之间的级别.我需要在一组T-SQL查询的上下文中,所以如果我能得到这样的结果集最好:

Month   Value
1/2009  1
2/2009  1
3/2009  2
4/2009  2
5/2009  2
6/2009  3

请注意,对于每个月,我们要么获取事务中指定的值,要么获取最新的非null值.

我的问题是我不知道该怎么做!我只是一个“中级”sql开发人员,我不记得曾经见过这样的事情.当然,我可以在程序中创建我想要的数据,或者使用游标,但我想知道是否有更好的,面向集合的方法来执行此操作.

我正在使用sql Server 2008,所以如果任何新功能都有帮助,我想听听它.

附:如果有人能够想出一个更好的方式来陈述这个问题,甚至是更好的主题,我会非常感激.我花了很长时间才决定“传播”,而跛脚,是我能想到的最好的. “涂片”听起来更糟糕.

解决方法

我首先构建一个Numbers表,其中包含从1到100万左右的连续整数.一旦掌握了它,它们就会变得非常方便.

例如,以下是如何获得2008年每月的第1天:

select firstOfMonth = dateadd( month,n - 1,'1/1/2008')
from Numbers
where n <= 12;

现在,您可以使用OUTER APPLY将它们放在一起,以查找每个日期的最新事务,如下所示:

with Dates as (
    select firstOfMonth = dateadd( month,'1/1/2008')
    from Numbers
    where n <= 12
)
select d.firstOfMonth,t.TransactionValue
from Dates d
outer apply (
    select top 1 TransactionValue
    from Transactions
    where TransactionDate <= d.firstOfMonth
    order by TransactionDate desc
) t;

这应该可以为您提供所需的内容,但您可能需要谷歌一点点找到创建Numbers表的最佳方法.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...