我有一个简单的选择查询,根据日期范围提供输出:
Declare @prevDate as Date
@prevDate = (Select Max(myDates) From Top40Table Where mydates < '2012/05/03' And PrimID=1)
Select
myDates, (P1/(Lag(P1) Over (Order by myDates))-1) As myRet
From
Top40Table
Where
(myDates Between @prevDate and '2012/05/10')
And PrimID = 1
这是典型的结果集:
myDates myRet
2012-05-02 NULL
2012-05-03 -0.0173786439241019
2012-05-04 -0.0268509853003636
2012-05-07 -0.00941786149400936
2012-05-08 -0.0134267235683988
2012-05-09 0.00633992501692782
2012-05-10 0.0203276794347731
选择查询是正确的并且做了它应该做的事情,获得prevDate 2012/05/02以进行计算。但是我不希望2012 {05 {02}行在myRet
列中具有NULL输出。我可以将myDates
和myRet
数据插入临时表(@TempTable
),然后只选择myDates
和myRet
,其中myRet
是那张桌子没有空。
有没有更简单的方法来创建@TempTable
然后另一个选择查询?我使用SQL Server 2012
答案 0 :(得分:2)
使用子查询:
select *
from (
select myDates
, (P1/(Lag(P1) Over (Order by myDates))-1) As myRet
from Top40Table
where myDates Between @prevDate and '2012/05/10'
and PrimID = 1
) as SubQueryAlias
where myRet is not null
答案 1 :(得分:-1)