根据codeigniter和sql中的类别计算单词

时间:2017-08-07 04:51:51

标签: mysql codeigniter

我发现基于报告表生成报告存在问题,详情请查看:

我的SQL表

+----+-----+------------+--------------+
| No | ID  | Asset      | Link         |      
+----+-----+------------+--------------+
| 1  | 203 | Asset A    | Clear        |  
| 2  | 204 | Asset B    | Clear        | 
| 3  | 205 | Asset A    | Not Clear    |  
| 4  | 206 | Asset A    | Not Clear    |  
| 5  | 208 | Asset A    | Need Confirm |  
| 6  | 210 | Asset B    | Clear        |   
| 7  | 212 | Asset B    | Not Clear    |  
| 8  | 213 | Asset B    | Clear        |  
| 9  | 214 | Asset A    | Clear        |  
| 10 | 215 | Asset B    | Need Confirm |   
| 11 | 216 | Asset B    | Need Confirm |      
+----+-----+------------+--------------+

基于上表,我想显示如下信息:

+----+--------------+-------+-----------+--------------+
| No | Count Asset  | Clear | Not Clear | Need Confirm | 
+----+--------------+-------+-----------+--------------+    
| No | Asset A      |   2   |     2     |       1      |  
| No | Asset B      |   3   |     1     |       2      |   
+-------------------+-------+-----------+--------------+ 
|  Total            |   5   |     3     |       3      |    
+-------------------+-------+-----------+--------------+

我已经阅读了一些关于sql中的数据透视表的参考资料,尝试了这段代码:

控制器:

$data_get= $this->db->query("SELECT asset,  
                        COUNT(CASE WHEN (link='Clear') THEN 1 ELSE 0 END) as clear,
                        COUNT(CASE WHEN (link='Not Clear') THEN 1 ELSE 0 END) as not_clear,
                        COUNT(CASE WHEN (link='Need Confirmation') THEN 1 ELSE 0 END) as need_confirm
                        FROM tbl_master GROUP BY asset");

观点:

<?php
    foreach($data_get->result_array() as $dp)
    {
    ?>
      <tr>
        <td><?php echo $dp['asset']; ?></td>
        <td><?php echo $dp['clear']; ?></td>
        <td><?php echo $dp['not_clear']; ?></td>
        <td><?php echo $dp['need_confirm']; ?></td>
      </tr>
     <?php
        }
     ?>

从上面的代码我得到一个错误,那里有未定义的变量.. 我是新手,如果有更正或任何建议,请告知,谢谢

1 个答案:

答案 0 :(得分:3)

控制器:

第一名:您需要获得控制器中的resultsend the resultview,如下所示。

第二名:并按照@Tim Biegeleisen回答。你需要使用sum

$data_get['result'] = $this->db->query("SELECT asset,  
                        SUM(CASE WHEN link = 'Clear'             THEN 1 ELSE 0 END) AS clear,
                        SUM(CASE WHEN link = 'Not Clear'         THEN 1 ELSE 0 END) AS not_clear,
                        SUM(CASE WHEN link = 'Need Confirmation' THEN 1 ELSE 0 END) AS need_confirm
                        FROM tbl_master GROUP BY asset")->result_array();

$this->load->view ('home', $data_get);  

在视图中:

foreach($result as $row){

}