【问题标题】:How to get the count of a specif value from a single column如何从单个列中获取特定值的计数
【发布时间】:2019-12-02 09:00:26
【问题描述】:

我正在处理一个想要获取列中值的计数的项目。我会用一个例子来解释。 我有一个名为 name 的表列。它的值是A,B,C,D,A,D,B,A,C。 现在我希望输出为

Count: A-3,B-2,C-2,D-2. 

我尝试过使用 group by 和 distinct。但两者都没有给我想要的东西。这一切都得到了该项目的总数。在下面给出的代码中是我尝试过的查询。那里我想要particulars_id 的计数,$public_page_id 对于我正在获取的所有particulars_id 都是通用的。表格中会有多个public_page_id,每个下面都会有一些particulars_id

    $output = '';
    $this->db->select('COUNT(service_appointment_details.particulars_id) 
    as count,particulars.particulars_name');
    $this->db->from('particulars');
    $this->db->group_by('particulars.particulars_id');
    $this->db->where('particulars.public_page_id',$public_page_id);
    $this->db- 
    >join('service_appointment_details','particulars.public_page_id = 
    service_appointment_details.public_page_id','right');
    $this->db->where($where_date);
    $query = $this->db->get();

预期结果

预期结果是(基于上面的例子)

Count: A-3,B-2,C-2,D-2.

实际结果

但我现在得到的是

Count: A-9,B-9,C-9,D-9.

我需要获取给定public_page_id 下每个particulars_id 的计数

【问题讨论】:

  • service_appointment_detailsparticulars 中是否有 9 行?您尝试过 inner join 吗?
  • 这只是一个例子。实际上,我有 3 个particular_id。这三个中,一个有两排,一个有1排。第三个暂时没有任何行。所以输出应该显示计数为row1-2 row2-1 row3-0

标签: php sql codeigniter count


【解决方案1】:

正如@scaisEdge 所指出的,您需要使用count(*) 而不是count(service_appointment_details.particulars_id)。通过使用count(service_appointment_details.particulars_id),您基本上可以计算您选择的行数,这不是您想要的。

最终的 sn-p 将是:

$output = '';
$this->db->select('COUNT(*) as count, particulars.particulars_name');
$this->db->from('particulars');
$this->db->group_by('particulars.particulars_name');
$this->db->where('particulars.public_page_id',$public_page_id);
$this->db->join('service_appointment_details','particulars.public_page_id = service_appointment_details.public_page_id','right');
$this->db->where($where_date);
$query = $this->db->get();

每当您想计算列值的出现次数时,您都会这样做

SELECT column_to_count, count(*) FROM table GROUP BY column_to_count

【讨论】:

  • 你提到了By using count(service_appointment_details.particulars_id), you basically count the number of rows from your select。这就是我要的。我不想要总数。无论如何,您给出的代码也产生了与我相同的结果。
  • 那么您要查找的是每个nameparticulars_id 的数量?
  • 正如我上面提到的,我将在 where 条件下有一个 public_page_id。每个public_page_id都会有一组particulars_id(在表中,会有一组public_page_ids)。所以我想要的是where子句中public_page_id下每个particular_id的计数。
【解决方案2】:

你应该使用 count(*)

 $this->db->select('COUNT(*) as count,particulars.particulars_name');
 ........

【讨论】:

  • 这没有任何改变
猜你喜欢
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多