2011-04-02 51 views
2

這是我的SQL代碼MySQL - 如何消除NULL值的結果? (有代碼)

SELECT p.plant_name, 
     sum(data.value_1) totalvalue_1 
    FROM (SELECT DISTINCT date_format(date, '%Y-%m') ym 
      FROM data 
     WHERE data.id_fk = 1 
      AND date BETWEEN '2011-01-01' AND '2011-04-01') dates 
CROSS JOIN (SELECT DISTINCT data.id_fk, 
        data.plant_id_fk 
       FROM data 
      WHERE data.id_fk = 1) up 
     JOIN plants p ON p.plant_id = up.plant_id_fk 
LEFT JOIN data ON date_format(data.date, '%Y-%m') = dates.ym 
       AND up.id_fk = data.id_fk 
       AND up.plant_id_fk = data.plant_id_fk 
       AND category_1 = 'expenses' 
    GROUP BY up.plant_id_fk 
    ORDER BY up.id_fk, up.plant_id_fk 

其輸出這個結果

aasd 74 
qweqwe 20 
tyutyu NULL 
bnmbnm NULL 
234234 NULL 

我想完全消除含有NULL的結果,並得到僅以此作爲我的結果:

aasd  74 
qweqwe 20 

我試過在幾個子句中使用is not null,但沒有給出我需要的結果。

有什麼建議嗎?

回答

7

嘗試添加HAVING條款您GROUP BYORDER BY之間:

group by up.plant_id_fk 
HAVING SUM(data.value_1) > 0 
+0

正確的一個就在這裏! – Kangkan 2011-04-02 05:03:41

+0

真棒 - 感謝一羣 – pepe 2011-04-02 05:05:13

+0

@torr - 嘿,我的榮幸!謝謝! – 2011-04-02 05:30:43