mysql:如果求和则嵌套

时间:2016-12-06 16:57:59

标签: mysql if-statement nested

我想计算一下,如果promotion_id是1483或1887,confirm_at不为null的次数。

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语句中这样做。我不想添加“where”。

事实上,我能够这样做:

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

2 个答案:

答案 0 :(得分: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,可以在AND测试中使用IF

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

答案 1 :(得分: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