2014-11-03 67 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

相關問題