带有多个'WHEN'值的mysql'case'

时间:2013-02-07 13:53:23

标签: mysql case

我有一个查询需要对其他2列为真的列进行计数。 当'DealerName'像'%MINI%'和'DealerContact_Y'= 1时,我需要计算'DealerName'

但我不确定语法。此查询产生错误

SELECT DealerName,
       count(DealerShipId) as dealersContacted,
       CASE WHEN
       DealerName LIKE "%MINI%", WHEN DealerContact_Y = 1
       THEN Count(DealerContact_Y) END as Mini_contacted_yes,
       Campaign, 
       DealerId 
       FROM tblsummaryResults

有没有办法在案例陈述中做多个WHENS?

2 个答案:

答案 0 :(得分:4)

您可以使用DealerName LIKE '%MINI%' AND DealerContact_Y = 1

以这种方式编写
SELECT DealerName,
  count(DealerShipId) as dealersContacted,
  count(CASE 
          WHEN DealerName LIKE '%MINI%' 
              AND DealerContact_Y = 1
          THEN DealerContact_Y END) as Mini_contacted_yes,
  Campaign, 
  DealerId 
FROM tblsummaryResults

答案 1 :(得分:1)

所以,算这样算:

COUNT(
  IF(DealerName LIKE "%MINI%" AND DealerContact_Y = 1, DealerContact_Y, NULL)
) AS Mini_contacted_yes