2014-11-03 65 views
1

我有2个表格,'部门'和'文件'。如何计算具有相同列数据的行数并显示到表中?

department

| doc_id |  dept_name  | 
---------------------------------- 
|  1 | Information Technology| 
|  2 | Software Development | 
|  3 | Human Resource  | 
|  4 | Accounting   | 
|  5 | Support    | 

document

| doc_id | doc_name | author | description | department    | 
---------------------------------------------------------------------------- 
|  1 | Maps  | User1 | sample  | Information Technology | 
|  2 | Audits  | User3 | sample  | Software Development | 
|  3 | Image  | User1 | sample  | Information Technology | 
|  4 | Papers  | User4 | sample  | Human Resource   | 
|  5 | Print Screen| User1 | sample  | Software Development | 
|  6 | Transaction | User3 | sample  | Accounting    | 
|  7 | Graph  | User1 | sample  | Support    | 
|  8 | Excel  | User1 | sample  | Information Technology | 

现在,我想有两列显示表:部门和total_doc。

输出:

|  department  |total_doc| 
----------------------------------- 
| Information Technology| 3  | 
| Software Development | 2  | 
| Human Resource  | 1  | 
| Accounting   | 1  | 
| Support    | 1  | 

我想要显示的部门内的总文档并以升序排列。

这是我的查询。(不知道)

SELECT department, count(doc_name) as 'total_doc' FROM tbl_document GROUP BY doc_name

我使用MVC模式的笨。

$this->db->select("department, count(doc_name) as 'total_doc'"); 
$this->db->from('document'); 
$this->db->group_by('doc_name'); 

此外,我怎样才能在表中显示这个?喜欢在HTML中使用foreach?

+0

你能送我.sql文件,这样我可以通过做测试为您提供在我的系统中。 – 2014-11-03 09:09:14

+0

我不能!我只是在我们的组织中维护一个程序,我的一些数据是保密的。 – jned29 2014-11-03 09:12:56

回答

1

您需要按department进行分组,而不是doc_name

$this->db->select("department, count(doc_name) as 'total_doc'"); 
$this->db->from('document'); 
$this->db->group_by('department'); 
$result = $this->db->get()->result(); 

希望这会帮助你。

foreach ($result as $row) 
{ 
    echo $row->department."----".$row->total_doc; 
} 
+0

我想在我的html中显示表格并使用foreach获取数据 – jned29 2014-11-03 09:20:32

+0

的输出是3 3 3 3 3,似乎只有第一个部门显示正确的输出,但它在所有行上打印相同的输出 – jned29 2014-11-03 09:22:15

+0

看到我的更新回答 – 2014-11-03 09:23:28

0

需要每个部门一行。 IN SQL单词:你想按分组

select department, count(*) as total_doc from document group by department; 

(顺便说一句:请不要使用单引号列别名)

1

在这里你去

SELECT dept_name,COUNT(td.department) FROM department d 
LEFT JOIN tdocument td ON td.`department`=d.`dept_name` 
GROUP BY td.`department` ORDER BY COUNT(td.`department`) DESC; 
+0

我已将文档重命名为tdocument,因为我有另一张同名的表 – 2014-11-03 09:38:29

+0

+1。有用!多谢兄弟。 – jned29 2014-11-03 09:42:50

相关问题