2016-12-06 48 views
0

我想指望有多少次confirmed_at沒有空給一個promotion_id或者是1483或1887年。MySQL的:如果嵌套總結

select 
    IF(promotion_id IN(1483,1887), sum(IF(confirmed_at IS NOT NULL,1,0)),0) as all_us_vs_voda, 
    status_inv 
from blabla 

group by status_inv 

例子:

promotion_id status_inv confirmed_at 
1   'before' 2016-05 
1483   'before' NULL 
1483   'after'  2016-05 
1483   'after'  2016-07 
1887   'before' 2016-08 
1887   'before' 2017-09 
1887   'after' 2017-09 

因此,其結果必然成爲:

status_inv not_nul_specific_promotions 
before  2 
after  3 

PS。我想在select語句中做到這一點。我不想添加「哪裏」。

事實上,我能夠這樣做:

sum(IF(promotion_id IN(1483,1887), IF(confirmed_at IS NOT NULL,1,0),0)) as all_us_vs_voda, 

回答

0

IN測試WHERE子句中,所以你只算那些行:

SELECT status_inv, SUM(IF(confirmed_at IS NOT NULL, 1, 0) AS not_nul_specific_promotions 
FROM blabla 
WHERE promotion_id IN (1483, 1887) 
GROUP BY status_inv 

你也不需要IF,因爲在MySQL中,對於TRUEFALSE,布爾值評估爲1和0。

SELECT status_inv, SUM(confirmed_at IS NOT NULL) AS not_nul_specific_promotions 
FROM blabla 
WHERE promotion_id IN (1483, 1887) 
GROUP BY status_inv 

你也可以只使用COUNT(confirmed_at)代替SUM(),因爲COUNT()只統計非空值。

SELECT status_inv, COUNT(confirmed_at) AS not_nul_specific_promotions 
FROM blabla 
WHERE promotion_id IN (1483, 1887) 
GROUP BY status_inv 

或者把兩個試驗中WHERE

SELECT status_inv, COUNT(*) AS not_nul_specific_promotions 
FROM blabla 
WHERE promotion_id IN (1483, 1887) AND confirmed_at IS NOT NULL 
GROUP BY status_inv 

如果你不想使用WHERE,你可以在IF測試使用AND

SELECT status_inv, SUM(IF(confirmed_at IS NOT NULL AND promotion_id IN (1483, 1887), 1, 0) AS not_nul_specific_promotions 
FROM blabla 
GROUP BY status_inv 
+0

我編輯了我的問題。 – Tonja

+0

我已經添加了另一個版本的答案,但我不明白你爲什麼不能使用'WHERE'? – Barmar

0

您可以使用count爲此,這裏是查詢:

select STATUS_INV,count(case when PROMOTION_ID=1483 THEN 1 when PROMOTION_ID =1887 THEN 1 ELSE NULL END) 
as confirmed_at FROM sample WHERE confirmed_at IS NOT NULL group by STATUS_INV