我有一个表格,我有两列briefeng
和briefbng
,我需要以正确的方式计算总空值而不是空值:
这是我的sql代码:
SELECT
Sum(If(brief_english Is Null, 1, 0)) AS briefeng,
Sum(If(brief_english Is NOT Null, 1, 0)) AS briefengnotnull,
Sum(If(brief_bangla Is Null, 1, 0)) AS briefbng
FROM synopsis;
但它会以这种方式返回结果:
+----------+-----------------+----------+
| briefeng | briefengnotnull | briefbng |
+----------+-----------------+----------+
| 946 | 896 | 841 |
+----------+-----------------+----------+
但我需要这样的结果
+----------+--------------+
| status | total |
+----------+--------------+
| briefeng | 946 |
+----------+--------------+
| briefengnotnull | 896 |
+----------+--------------+
| briefengnotnull | 841 |
+----------+--------------+
我该怎么做?我无法找到一种简单有效的方式。
答案 0 :(得分:0)
使用union或union都是这样的:
SELECT
'briefeng' as status,
Sum(If(brief_english Is Null, 1, 0)) AS total
FROM synopsis
UNION ALL
SELECT
'briefengnotnull' as status,
Sum(If(brief_english Is NOT Null, 1, 0)) AS total
FROM synopsis
UNION ALL
SELECT
'briefbng' as status,
Sum(If(brief_bangla Is Null, 1, 0)) AS total
FROM synopsis
答案 1 :(得分:0)
SELECT count(*) FROM tablename WHERE a IS NULL
UNION ALL
SELECT count(*) FROM tablename WHERE a IS NOT NULL
或
select sum(case a when null then 1 else 0) "Null values",
sum(case a when null then 0 else 1) "Non-null values"
from tablename;
或
select sum(case when a is null then 1 else 0 end) count_nulls
, count(a) count_not_nulls
from tablename;
答案 2 :(得分:0)
这是一个钩子或骗子的方法但是如果你创建一个包含这个模式的标题的辅助表
CREATE TABLE `titles` (
`title` varchar(255) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`title`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin
和这个数据
insert into `titles`(`title`) values ( 'briefeng'), ( 'briefengnotnull'), ( 'briefbng');
使用此查询
SELECT t.title, IF(a.total IS NOT NULL, a.total, IF(b.total IS NOT NULL, b.total, c.total)) AS total FROM
titles t
LEFT JOIN (SELECT 'briefeng' AS title, SUM(IF(brief_english IS NULL, 1, 0)) AS total FROM synopsis) a ON a.title=t.title
LEFT JOIN (SELECT 'briefengnotnull' AS title, SUM(IF(brief_english IS NULL, 0, 1)) AS total FROM synopsis) b ON b.title=t.title
LEFT JOIN (SELECT 'briefbng' AS title, SUM(IF(brief_bangla IS NULL, 1, 0)) AS total FROM synopsis) c ON c.title=t.title
获取此结果(取决于概要表中的记录)
+-----------------+-------+
| title | total |
+-----------------+-------+
| briefbng | 3 |
| briefeng | 1 |
| briefengnotnull | 4 |
+-----------------+-------+