SQL Query帮助我在列中找不到“y”

时间:2013-07-01 08:28:48

标签: php mysql

我希望显示日期中有多少“y”

我想知道是否有这样的事情:(

我想在2013.01.01栏中显示“Y”的数量

<?php
$link = mysql_connect("localhost", "", "");
mysql_select_db("", $link);
$result = mysql_query("SELECT * FROM attendance WHERE date = '2013.01.01'", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows";
?>

我的表(出勤)

date        pt17   pt18    pt19    pt20     pt21     pt22     pt23    pt24

2013.01.01    y     n        y       n         y               y        n
2013.01.02    n     n        y                 y      y        y        n
2013.01.03    n     y        n       y         n      y        n        n
  ......

DESIRE OUTPUT:

no. of presents on 2013.01.01 are 4

4 个答案:

答案 0 :(得分:1)

SELECT concat("no. of presents on ",date," are", 
if(pt17='y',1,0)+
if(pt18='y',1,0)+
if(pt19='y',1,0)+
if(pt20='y',1,0)+ 
if(pt21='y',1,0)+ 
if(pt22='y',1,0)+ 
if(pt23='y',1,0)+
if(pt24='y',1,0) )
 FROM attendance WHERE date = '2013.01.01'

答案 1 :(得分:1)

你的基础SQL查询是

SELECT COALESCE((pt17 = 'y'), 0)
      +COALESCE((pt18 = 'y'), 0)
      +COALESCE((pt19 = 'y'), 0)
      +COALESCE((pt20 = 'y'), 0)
      +COALESCE((pt21 = 'y'), 0)
      +COALESCE((pt22 = 'y'), 0)
      +COALESCE((pt23 = 'y'), 0)
      +COALESCE((pt24 = 'y'), 0) num
  FROM attendance
 WHERE date = '2013.01.01'

输出:

| NUM |
-------
|   4 |

这是 SQLFiddle 演示


您的php部分,假设您仍然使用mysql_扩展名可能看起来像

$link = mysql_connect('localhost', 'user', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('dbname', $link);
if (!$db_selected) {
    die ('Can\'t use db : ' . mysql_error());
}

$date = '2013.01.01';

$sql = "SELECT COALESCE((pt17 = 'y'), 0)
              +COALESCE((pt18 = 'y'), 0)
              +COALESCE((pt19 = 'y'), 0)
              +COALESCE((pt20 = 'y'), 0)
              +COALESCE((pt21 = 'y'), 0)
              +COALESCE((pt22 = 'y'), 0)
              +COALESCE((pt23 = 'y'), 0)
              +COALESCE((pt24 = 'y'), 0) num
          FROM attendance
         WHERE date = '$date'";

$result = mysql_query($sql);
if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}
if ($row = mysql_fetch_assoc($result)) {
    $num_of_present = $row['num'];  
}
echo "no. of presents on 2013.01.01 are $num_of_present";

答案 2 :(得分:0)

<?php
$link = mysql_connect("localhost", "vishnu65_ven", "vishnu65_ven");
mysql_select_db("vishnu65_ven", $link);
$result = mysql_query("SELECT * FROM attendance WHERE date = '2013.01.01'", $link);
while($rows = mysql_fetch_rows($result)){
    $num_of_y = 0;
    foreach($rows as $row){
         if($row == 'y')
            $num_of_y++;
    }
    echo 'Number of y = '.$num_of_y;
}

?>

答案 3 :(得分:0)

peterm和chetan已经给出了简单的答案。所以我只是提供一个替代解决方案。我不确定ptXX-columns的上下文是什么,但它们似乎是通用的。如果是这样,最好将表重组为以下内容。

Attendance
DATE | PT-ID | status(y/n/_)

(如有必要,添加一个定义PT-ID的表格)
使用此表结构,您可以轻松地请求在特定日期出席,而无需使用此处给出的高级(以及我认为硬编码)查询。

相关问题