2016-12-06 45 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