2016-08-18 54 views
0

我想運行下面的查詢,但是當子查詢試圖返回值不存在的條件時出現錯誤。SQL子查詢返回Null,如果沒有數據發現匹配條件

有人可以請指教最簡單的方法來強制默認返回值,如果子查詢的where條件返回空白。

我得到一個錯誤,我使用的日期沒有記錄數據,它給我一個錯誤並退出。

我試圖獲得一些R分析的數據。

使用運行時

SELECT ah1.DateTime,ah1.Value as TPH, 
(select value 
from dbo.AnalogHistory 
where tagname = 'CR_CR001_SPEED.PVAI' 
and datetime = ah1.DateTime 
) as CR_SPEED, 

(select value 
from dbo.AnalogHistory 
where tagname = 'CR_CR001_MOTOR_I.PVAI' 
and datetime = ah1.DateTime 
) as EM_Current, 

(select value 
from dbo.AnalogHistory 
where tagname = 'CR_TE741023G.PVAI' 
and datetime = ah1.DateTime 
) as EM_NDE, 

(select value 
from dbo.AnalogHistory 
where tagname = 'CR_TE741023H.PVAI' 
and datetime = ah1.DateTime 
) as EM_DE 

    FROM [Runtime].[dbo].[AnalogHistory] ah1 
    where TagName = 'CR_WQI752010.PVAI' 
    and wwResolution = '600000' 
    and DateTime > '20160816' 
    and wwRetrievalMode = 'cyclic' 
+0

如果你的問題是,你有沒有結果集,因爲'日期時間>「20160816''返回結果,你將不得不使用'IF EXISTS(SELECT 1 FROM myTable WHERE )BEGIN ...(我的查詢結果是否存在)... END ELSE BEGIN ...(我的查詢如果沒有結果集)... END' – ZLK

+0

嗨ZLK,其他查詢返回數據如預期的那樣以10分鐘的間隔運行並且運行約20秒,然後由於日期相關性而未找到CR_TE741023H上未發現的數據錯誤而崩潰。這是由於通信問題導致數據未收集的一段時間。 – GlenCloncurry

+0

你真的得到了什麼錯誤? – ZLK

回答

0

如果我理解正確的話,你並不真的需要所有這些correlated subqueries。下面是使用conditional aggregation另一種選擇:

select DateTime, 
     max(case when TagName = 'CR_WQI752010.PVAI' then Value end) as TPH, 
     max(case when TagName = 'CR_CR001_SPEED.PVAI' then Value end) as CR_SPEED, 
     max(case when TagName = 'CR_CR001_MOTOR_I.PVAI' then Value end) as EM_Current, 
     max(case when TagName = 'CR_TE741023G.PVAI' then Value end) as EM_NDE, 
     max(case when TagName = 'CR_TE741023H.PVAI' then Value end) as EM_DE 
from [Runtime].[dbo].[AnalogHistory] 
where TagName in ('CR_WQI752010.PVAI', 'CR_CR001_SPEED.PVAI', 'CR_CR001_MOTOR_I.PVAI', 
        'CR_TE741023G.PVAI', 'CR_TE741023H.PVAI') 
     and DateTime > '20160816' 
group by DateTime 
having max(case when TagName = 'CR_WQI752010.PVAI' then wwResolution end) = '600000' and 
     max(case when TagName = 'CR_WQI752010.PVAI' then wwRetrievalMode end) = 'cyclic'