如果当前列值为空,则从下一行获取同一列的值

时间:2019-07-08 12:26:41

标签: sql sql-server stored-procedures

我有一个表,我想选择一个列,例如未找到记录(因为我与其他表联接)或存在,但比从下一行选择同一列的值为空。我尝试使用isnull和合并函数,但无法获取下一行的值。 任何帮助或链接将不胜感激。

这是我到目前为止的查询

Select 
  (select top 1 OpenPrice from #tbltempData where Dated=D.Dated) [Open],
  ISNULL((select top 1 ClosePrice from #tbltempData where Dated= DATEADD(hour,@Interval-1, D.Dated)),
  (select top 1 ClosePrice from #tbltempData where Dated= DATEADD(hour,0, D.Dated))) [Close], 
  [Min],[Max],Dated
from #tbltempData2 D
Order BY Dated Asc

打开列的值为空。

这是我的示例数据的屏幕截图enter image description here

这是输出越来越 enter image description here

详细信息:由于我的样本数据中有日期为'28 / 06/2019'的记录,并且第一次记录的时间是上午9点,因此我将在2小时内对数据进行分组,因此在对同一日期的第一组记录进行分组之后上午8点,并且由于我当时在样本数据中没有任何价值,因此获得了空值。为了避免这种情况,我想获取OpenPrice值,其中时间是同一日期的上午9点(在示例数据中),因为该时间在同一组中。

2 个答案:

答案 0 :(得分:1)

如果您希望“下一行”始终大于当前时间

[Open] = (
       select top 1 OpenPrice 
       from #tbltempData t 
       where DATEDIFF(day,t.Dated,D.Dated) = 0   -- make sure the price for same day
         AND t.Dated>=D.Dated 
       ORDER BY t.Dated ASC
) 

如果您希望“下一行”最接近可用时隙

 [Open] = (
       select top 1 OpenPrice 
       from #tbltempData t 
       where DATEDIFF(day,t.Dated,D.Dated) = 0   -- make sure the price for same day
       ORDER BY ABS(DATEDIFF(minute,t.Dated,D.Dated)) ASC
) 

答案 1 :(得分:0)

我认为相关子查询可以满足您的需求:

select d.*,
       (select top (1) ClosePrice
        from #tbltempData td
        where td.Dated <= D.Dated
        order by td.Dated desc
       ) as ClosePrice
from #tbltempData2 d
order by dated Asc
相关问题