使用一个二进制字段从表中获取单独的值

时间:2015-01-31 15:48:21

标签: 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

但我认为我可以从一个查询而不是两个查询中获得两者。

4 个答案:

答案 0 :(得分:1)

select sum(present = 1) as present1,
       sum(present = 0) as present0
from table 

答案 1 :(得分:0)

您可以使用以下查询:

select (select count(*) from table where present=1) as "present"
      , (select count(*) from table where present=0) as "absent";

答案 2 :(得分:0)

试试这个工作正常:

SELECT SUM( present =1 ) AS present, SUM( present =0 ) AS absent
FROM details
WHERE id =1

屏幕截图:

enter image description here

答案 3 :(得分:0)

试试这个: 对于所有有小组的学生

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 clause,如下所示:

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'

希望这能帮到你..