怎样按照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表的最佳要领. (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |


