我有一张这样的桌子。
id ___ d1 ___ d2 ___ d3 ___ d4 ___ d5 ___ d6 ___ d7 ___ d8
----------------------------------------------------------
01 ___ XX ___ "" ___ "" ___ "" ___ "" ___ "" ___ "" ___ "" (There are 7 ""s)
02 ___ XX ___ XX ___ XX ___ "" ___ "" ___ "" ___ "" ___ "" (There are 5 ""s)
03 ___ XX ___ XX ___ "" ___ "" ___ "" ___ "" ___ "" ___ "" (There are 6 ""s)
04 ___ XX ___ "" ___ "" ___ "" ___ "" ___ "" ___ "" ___ "" (There are 7 ""s)
我希望看到这样的输出:
id ___ count
------------
01 ___ 7
02 ___ 5
03 ___ 6
04 ___ 7
我该怎么做?简单地说,我想计算空字符串,但在同一行。
答案 0 :(得分:2)
您可以使用case
语句,并将结果加起来:
SELECT
id
, ( CASE d1 WHEN '' THEN 1 ELSE 0 END
+ CASE d2 WHEN '' THEN 1 ELSE 0 END
+ CASE d3 WHEN '' THEN 1 ELSE 0 END
+ CASE d4 WHEN '' THEN 1 ELSE 0 END
+ CASE d5 WHEN '' THEN 1 ELSE 0 END
+ CASE d6 WHEN '' THEN 1 ELSE 0 END
+ CASE d7 WHEN '' THEN 1 ELSE 0 END
+ CASE d7 WHEN '' THEN 1 ELSE 0 END
) as TotalSpaces
FROM myTable
答案 1 :(得分:1)
我倾向于使用将布尔值视为整数的MySQL快捷方式:
select id,
((d1 = '') + (d2 = '') + (d3 = '') + (d4 = '') + (d5 = '') +
(d6 = '') + (d7 = '') + (d8 = '')
) as "Count"
from table t;