场景是我是管理员,我有一个会话,会话表由session_id,coach_name,日期(格式Y-m-d)组成。 现在我想计算每个“月”教练的总活动量。 所以我的观点是如何在SQL查询中获得此类输出。
所需的输出是每个教练每月的活动量。
Name | No. of session this month
Coach_name1 = 13
Coach_name2 = 5
这是我当前的查询,它给了我教练的名字,但我不知道如何获得每个月
public function getAll(){
$query = $this->db->query('SELECT DISTINCT coach_name FROM sessions);
return $query->result();
}
答案 0 :(得分:0)
在查询中使用MySQL MONTH()。所以基本上,如果您的会话表中包含所有数据,请在查询中尝试以下内容。
SELECT DISTINCT(`name`),COUNT(`name`) AS `activity` FROM `session`
WHERE MONTH(`date`)=8 GROUP BY `name`;
答案 1 :(得分:0)
你必须准备如下的查询:
select
coach_name,
month(your_date_field),
count(1)
from
your_table
where
month(your_date_field) = 8
group by
coach_name, month(your_date_field)
哪会返回如下记录,
| coach_name | month(your_date_field) | count(1) |
+---------------+------------------------+------------+
| Coach_name1 | 8 | x |
| Coach_name2 | 8 | x |
| Coach_name3 | 8 | x |
+---------------+------------------------+------------+
在codeigniter中
$this->db->select("coach_name, month(your_date_field) as month_number,count(1) as counts");
$this->db->where('month(your_date_field)',8);
$this->db->group_by('coach_name,MONTH(your_date_field)');
$query = $this->db->get('your_table');
// results
foreach ($query->result_array() as $row)
{
// do this to see array
print_r($row);
// to access individual fields
echo $row['coach_name'];
echo $row['month_number'];
echo $row['counts'];
}
答案 2 :(得分:0)
使用此查询获取结果。 使用mysql MONTH()从日期和组中获取月号。您将获得所有月份数据。
SELECT coach_name,
Count(*) AS activities
FROM sessions
WHERE Month(date) = 8 //for specfic month
GROUP BY coach_name, Month(date) // for all months
使用此查询根据系统日期动态获取当前月份
SELECT coach_name,
Count(*) AS activities
FROM sessions
WHERE Month(date) = MONTH(CURRENT_DATE()) //for selecting current month.
GROUP BY coach_name