Php 使用一个二进制字段从表中获取单独的值
我有如下学生出勤表:Php 使用一个二进制字段从表中获取单独的值,php,mysql,Php,Mysql,我有如下学生出勤表: id | Present | date 1 | 1 1 | 0 1 | 1 1 | 1 1 | 0 现在我想通过单个查询得到他在现场的总天数。可能吗 下面是我用来计算学生出席/缺席人数的方法: select count(*) from table where present =1 select count(*) from table where present =0 但是我想我可以从一个查询而不是两个查询中同时获得这两个查询。您可以使用以下查询: selec
id | Present | date
1 | 1
1 | 0
1 | 1
1 | 1
1 | 0
现在我想通过单个查询得到他在现场的总天数。可能吗
下面是我用来计算学生出席/缺席人数的方法:
select count(*) from table where present =1
select count(*) from table where present =0
但是我想我可以从一个查询而不是两个查询中同时获得这两个查询。您可以使用以下查询:
select (select count(*) from table where present=1) as "present"
, (select count(*) from table where present=0) as "absent";
试试这个,效果很好:
SELECT SUM( present =1 ) AS present, SUM( present =0 ) AS absent
FROM details
WHERE id =1
屏幕截图:
SELECT SUM( present =1 ) AS present, SUM( present =0 ) AS absent
FROM details
WHERE id =1
试试这个:
适用于所有分组的学生
select id,present,absent from
(
select id,sum(case when present = 1 then 1 else 0 end) as present,
sum(case when present = 0 then 1 else 0 end) as absent
from table_name
group by id
) as absen
如果只想显示一个学生,只需在末尾添加where子句
,如下所示:
select id,present,absent from
(
select id,sum(case when present = 1 then 1 else 0 end) as present,
sum(case when present = 0 then 1 else 0 end) as absent
from table_name
group by id
) as absen
where id = '1'
希望这对你有帮助