[英]summation in mysql does not work properly and returns 0
我有一個SQL查詢如下:
但是問題是,如果dataitem = 3的第二個選擇庫存返回null,則整個計算將變為0。例如,對於第一個選擇,我有100,而第二個選擇則返回null。 將它們相加應得到100,但它會返回0!
誰能說出原因以及消除這個的方法? 這也是可復制的代碼:
select( (
SELECT sum(Sentiment)
FROM entity_epoch_data
WHERE EpochID IN
(SELECT ID
FROM epoch
WHERE StartDateTime>='2013-11-1'
AND EndDateTime<='2013-11-30')
AND EntityID =86
AND DataitemType=0
)+
(SELECT sum(Sentiment)
FROM entity_epoch_data
WHERE EpochID IN
(SELECT ID
FROM epoch
WHERE StartDateTime>='2013-11-1'
AND EndDateTime<='2013-11-30')
AND EntityID =86
AND DataitemType=3)
)
只需將IFNULL
命令(例如IFNULL((select sum()......), 0)
添加到表示值的SQL中,它應該可以正常工作。
但是有點建議的和平。 您應該改進該查詢。 我相信這個查詢與您做同樣的事情。
SELECT sum(entity_epoch_data.Sentiment)
FROM entity_epoch_data INNER JOIN epoch
ON entity_epoch_data.EpochID = epoch.id
WHERE epoch.StartDateTime>='2013-11-1'
and epoch.EndDateTime<='2013-11-30'
AND entity_epoch_data.EntityID =86
and entity_epoch_data.DataitemType in (0,3)
您正在對DataitemType 3和0的總和求和,它只能是一個帶有聯接的查詢
添加null是不確定的,因此返回null或0。您可以使用CASE表達式來避免該問題。
SELECT SUM(CASE null = sentiment THEN 0 ELSE sentiment END) FROM ....
如果您的數據庫在SUM()函數中不支持CASE,則創建一個使用CASE將空值替換為0的VIEW。
使用CASE
語句而不是您正在使用的語句。
select sum(case when StartDateTime>='2013-11-1' and EndDateTime<='2013-11-30' and DataitemType=0 then Sentiment else 0 end) as Sentiment_0, sum(case when StartDateTime>='2013-11-1' and EndDateTime<='2013-11-30' and DataitemType=3 then Sentiment else 0 end) as Sentiment3 from (tables_joined) where EntityID =86
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.