mySQL统计字段值的实例
我有这样一个数据库表:mySQL统计字段值的实例,mysql,Mysql,我有这样一个数据库表: id slot1 slot2 slot3 --------------------------------- 1 10 10 0 2 0 0 10 3 0 10 0 我需要一个SQL语句来找出整个表中有多少个“10”的实例。因此,对于上面的问题,它会给我4作为答案。我不确定我能用什么方法 有没有一种合乎逻辑的方法可以做到这一点,或者我必须在slot1=10、slot2
id slot1 slot2 slot3
---------------------------------
1 10 10 0
2 0 0 10
3 0 10 0
我需要一个SQL语句来找出整个表中有多少个“10”的实例。因此,对于上面的问题,它会给我4作为答案。我不确定我能用什么方法
有没有一种合乎逻辑的方法可以做到这一点,或者我必须在slot1=10、slot2=10或slot3=10的位置提取所有记录,然后对它们进行计数?有一种方法可以通过条件聚合实现
select count(case when slot1=10 then 1 end) +
count(case when slot2=10 then 1 end) +
count(case when slot3=10 then 1 end)
from tbl
where 10 in (slot1,slot2,slot3)
使用MySQL,条件可以简化为
select sum(slot1=10)+sum(slot2=10)+sum(slot3=10)
from tbl
where 10 in (slot1,slot2,slot3)
根据真实性,每个条件返回1或0。使用条件聚合的一种方法
select count(case when slot1=10 then 1 end) +
count(case when slot2=10 then 1 end) +
count(case when slot3=10 then 1 end)
from tbl
where 10 in (slot1,slot2,slot3)
使用MySQL,条件可以简化为
select sum(slot1=10)+sum(slot2=10)+sum(slot3=10)
from tbl
where 10 in (slot1,slot2,slot3)
根据真实性,每个条件返回1或0。
sum(当slot1=10时,case为1,否则0结束+当slot2=10时,case为1,否则0结束+当slot3=10时,case为1,否则0结束)
数据库表不是电子表格。修复您的模式。sum(当slot1=10时为case,当slot2=10时为1 else 0 end+case,当slot3=10时为1 else 0 end+case,当slot3=10时为1 else 0 end)
数据库表不是电子表格。修复您的架构。匿名向下投票者可以说明原因吗?匿名向下投票者可以说明原因吗?