【问题标题】:How to count number of rows with the same column data and display to table?如何计算具有相同列数据的行数并显示到表格?
【发布时间】:2014-12-29 21:50:14
【问题描述】:

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

【问题讨论】:

  • 你能把 .sql 文件发给我,以便我可以通过在我的系统中进行测试来提供给你。
  • 我不能!我只是在我们的组织中维护一个程序,我的 sql 上的一些数据是机密的。

标签: php mysql sql-server codeigniter


【解决方案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;
}

【讨论】:

  • 我想在我的html中显示表格并使用foreach来获取数据
  • 输出为 3 3 3 3 3,好像只有第一个部门显示正确的输出,但它在所有行上都打印相同的输出
【解决方案2】:

给你

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;

【讨论】:

  • 我已将文档重命名为 tdocument,因为我有另一个同名的表
【解决方案3】:

您希望每个部门一行。用 SQL 的话来说:你想按部门分组

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 2018-11-20
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2013-08-19
    相关资源
    最近更新 更多