假设我有一个表,其数据如下:
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
答案 0 :(得分:1)
使用:
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
答案 1 :(得分:0)
如果你知道只有'single','married'和null作为选项,这将有效:
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
答案 2 :(得分:0)
SELECT SUM(IF(status='single' OR status IS NULL,1,0)) AS Single,
SUM(IF(status='married',1,0)) AS Married
FROM table