簡體   English   中英

如何計算具有相同列數據的行數並顯示到表?

[英]How to count number of rows with the same column data and display to table?

我有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 |

現在,我要顯示具有兩列的表:department和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

我在Codeigniter中使用MVC模式。

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

另外,如何在表格中顯示呢? 喜歡在HTML中使用foreach?

您需要按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;
}

干得好

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;

您要每個部門一行。 用SQL詞表示:您想按部門分組

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

(順便說一句:列別名不要使用單引號。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM