统计MySQL中的空数据

发布于 2024-09-25 07:41:17 字数 449 浏览 4 评论 0原文

假设我有一张表,其中包含如下数据:

name       status
bob        single
bob        single
jane       null
tina       null
shane      married

我想要如果状态“单一或数据为空”则表示单一。因此,如果数据为空,脚本可以将其读取为单个数据,并且可以一起计数。 所以我可以显示如下结果:

Single     Married
3            1

我已经尝试过这个,但它不起作用:

SELECT SUM(IF(status='single',1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table

let say i have one table, which have data like:

name       status
bob        single
bob        single
jane       null
tina       null
shane      married

i want if status "single or data null" it means single. so if data empty script can read it as single and can count together.
so i can show result like:

Single     Married
3            1

i have tried with this and it doesnt work:

SELECT SUM(IF(status='single',1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨轻弹 2024-10-02 07:41:17

使用:

SELECT SUM(CASE WHEN x.status = 'single' OR x.status IS NULL THEN 1 ELSE 0 END) AS single,
       SUM(CASE WHEN x.status = 'married' THEN 1 ELSE 0 END) AS married
  FROM (SELECT DISTINCT
               t.name,
               t.status
          FROM YOUR_TABLE t) x

Use:

SELECT SUM(CASE WHEN x.status = 'single' OR x.status IS NULL THEN 1 ELSE 0 END) AS single,
       SUM(CASE WHEN x.status = 'married' THEN 1 ELSE 0 END) AS married
  FROM (SELECT DISTINCT
               t.name,
               t.status
          FROM YOUR_TABLE t) x
生来就爱笑 2024-10-02 07:41:17

如果您知道只有“单身”、“已婚”和“空”作为选项,那么这将起作用:

SELECT SUM(IF(status!='married',1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table

否则请尝试

SELECT SUM(IF(status='single' OR status is null,1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table

If you know there are only 'single', 'married', and null as options, this will work:

SELECT SUM(IF(status!='married',1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table

Otherwise try

SELECT SUM(IF(status='single' OR status is null,1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table
夏天碎花小短裙 2024-10-02 07:41:17
SELECT SUM(IF(status='single' OR status IS NULL,1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table
SELECT SUM(IF(status='single' OR status IS NULL,1,0)) AS Single,
       SUM(IF(status='married',1,0)) AS Married
FROM table
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文