MySQL - 如何计算空值而不是空值?

时间:2022-01-05 09:35:54

I have a simple table of installs:

我有一个简单的安装表:

  • prod_code
  • prod_code
  • email
  • 电子邮件
  • install_slot
  • install_slot

If the install_slot is NULL, then it's an available install slot. Not null -- then, used slot. I need to return a result of total installs for a given product and email, as well as a result of used installs for a given product and email. I guess I could do this with two queries, but wondered if there's a SQL way to do it all in one?

如果install_slot为NULL,那么它是一个可用的安装槽。不为null - 然后,使用插槽。我需要返回给定产品和电子邮件的总安装结果,以及给定产品和电子邮件的已安装结果。我想我可以用两个查询做到这一点,但想知道是否有一种SQL方法可以在一个中完成所有操作?

I tried the following as a wild guess, but it didn't work.

我尝试了以下作为一个疯狂的猜测,但它没有奏效。

SELECT
    i1.`prod_code`,
    COUNT(i1.`email`) AS total_installs,
    COUNT(ISNULL(i2.`install_slot`)) AS used_installs
FROM
    `installs` AS i1
JOIN
    `installs` AS i2
ON
    i1.`prod_code` = i2.`prod_code`
WHERE
    i1.`email` = 'example@example.com'
GROUP BY
    i1.`prod_code`,i2.`prod_code`

2 个解决方案

#1


25  

SELECT prod_code,
       COUNT(email) AS total_installs,
       COUNT(install_slot) AS used_installs
FROM installs
WHERE email='example@example.com'
GROUP BY prod_code

COUNT counts NOT NULL values only.

COUNT仅计算NOT NULL值。

#2


3  

The solution offered did not work for me. I had to modify as follows:

提供的解决方案对我不起作用。我不得不修改如下:

SELECT prod_code,
       COUNT(NULLIF(email,'')) AS total_installs,
       COUNT(NULLIF(install_slot,'')) AS used_installs
FROM installs
WHERE email='example@example.com'
GROUP BY prod_code

#1


25  

SELECT prod_code,
       COUNT(email) AS total_installs,
       COUNT(install_slot) AS used_installs
FROM installs
WHERE email='example@example.com'
GROUP BY prod_code

COUNT counts NOT NULL values only.

COUNT仅计算NOT NULL值。

#2


3  

The solution offered did not work for me. I had to modify as follows:

提供的解决方案对我不起作用。我不得不修改如下:

SELECT prod_code,
       COUNT(NULLIF(email,'')) AS total_installs,
       COUNT(NULLIF(install_slot,'')) AS used_installs
FROM installs
WHERE email='example@example.com'
GROUP BY prod_code