1

我需要查询以在 15 分钟的时间段内获取我的数据表中的数据。如果值存在,我应该返回表中的值,或者我应该返回 null。怎么做

我这样写查询:

 with mycte as
  (
   select cast('2011-06-12 00:00:00' as datetime) DateValue 
   union all 
   select dateadd(minute,15,DateValue) 
   from mycte 
   where  dateadd(minute,15,DateValue) <= '2011-06-12 23:59:00'
   ) 
   select datetime,feederid,VR,VY,VB,IR,IY,IB,KW,KVA,KVAR,PF1,PF2,PF3,PF 
   from pseb.dbo.datasource, (
                              select meterid,DateValue 
                              from  mycte,pseb.dbo.METERMASTER 
                              )a 
   where CONVERT(datetime,datetime) >= DateValue 
     and CONVERT(datetime,DATETIME) < dateadd(minute,15,DateValue) 
     and feederid=a.MeterID 
   option (maxrecursion 32767)

但它仅返回表中存在的值。帮我做。。

4

1 回答 1

1

您需要使用 LEFT JOIN

;with mycte as
  (
   select cast('2011-06-12 00:00:00' as datetime) AS BeginDateValue, 
          dateadd(minute, 15, '2011-06-12 00:00:00') AS EndDateValue
   union all 
   select dateadd(minute, 15, BeginDateValue), 
          dateadd(minute, 15, EndDateValue)
   from mycte 
   where  dateadd(minute, 15, BeginDateValue) <= '2011-06-12 23:59:00'
   )
   SELECT [datetime], feederid, VR,VY,VB,IR,IY,IB,KW,KVA,KVAR,PF1,PF2,PF3,PF
   FROM mycte mc LEFT JOIN pseb.dbo.datasource d 
                   ON CONVERT(datetime, [datetime]) >= BeginDateValue 
                     and CONVERT(datetime, [DATETIME]) < EndDateValue
                 LEFT JOIN pseb.dbo.METERMASTER m ON d.feederid = m.MeterID
于 2013-02-15T12:00:10.063 回答