CTE 查询不返回任何结果

CTE query Not returning any result

以下查询有效

select TOP 100 T.DWH_ID,T.date_time, T.TimeDiff, T.[End Date], T.SPS_Bereich, T.txtName from (  
SELECT sto.[DWH_ID]
      ,sto.[SPS_Bereich]
      ,FORMAT(sto.[DateTime], 'dd-MM-yyyy HH:mm') as date_time
      ,sto.[txtName]
      ,sto.[TimeDiff]
      , DATEADD(second,sto.[TimeDiff],FORMAT(sto.[DateTime], 'dd-MM-yyyy HH:mm'))as [End Date]
  FROM [Stoerdaten].[sta].[Stoerungen]  sto where sto.Classname='Alarm' and sto.TimeDiff>60 ) as T

  join  [IgnitionServer].[dbo].[scheduled_events_ISTProduction] cal on 

  ((T.date_time between cal.start_date and cal.end_date) and T.[End Date] between cal.start_date and cal.end_date) where cal.typ=1 order by [DWH_ID] desc

但是当我改为 CTE 时,它没有给我任何结果。

CTE 查询

;with q1 as 
  (
  select TOP 1000 [DWH_ID], 
  SPS_Bereich ,
  FORMAT([DateTime], 'dd-MM-yyyy HH:mm') as date_time,
   [txtName],
    [TimeDiff]
    , DATEADD(second,[TimeDiff],FORMAT([DateTime], 'dd-MM-yyyy HH:mm'))as [End_Date]
  FROM [Stoerdaten].[sta].[Stoerungen] where Classname='Alarm' and TimeDiff>60 
  )

  select q1.DWH_ID,
  q1.date_time, 
  q1.TimeDiff, q1.[End_Date], q1.txtName, q1.SPS_Bereich   from  q1 join [IgnitionServer].[dbo].[scheduled_events_ISTProduction] cal on 
  ((q1.date_time between cal.start_date and cal.end_date) and q1.[End_Date] between cal.start_date and cal.end_date)  where cal.typ=1 

我不明白我在这里错过了什么。非常感谢任何帮助。

您的 CTE 包含 [sta].[Stoerungen] 中符合 WHERE 标准的前 1000 条记录,然后您从中加入 [scheduled_events_ISTProduction]

在您的初始查询中,您将在 JOIN 完成后返回前 100 个 ,所以我想无论出现在 CTE 结果中的是什么加入 [scheduled_events_ISTProduction].

中的记录

如果您只是 select CTE 中的所有内容,您应该会看到其中最多有 1000 条记录,但也应该能够验证 JOIN 问题。