I have a table with 2 fields. Id_user first field and the second field type of browser, I tried to make a percentage of the total number of users favorite browser based user. after I try to make her its query results do not match a percentage of her, what's wrong?
|id_user| name_item
--------------------------
| 1 | safari |
| 2 | firefox |
| 3 | opera mini |
| 4 | safari |
| 5 | chrome |
| 6 | firefox |
| 7 | chrome |
| 8 | chrome |
| 9 | firefox |
| 10 | firefox |
| 11 | safari |
| 12 | opera mini |
which are expected
| safari | 25% |
| opera mini | 17% |
| firefox | 33% |
| chrome | 25% |
Controllers
public get_json() {
$browser = $this->My_model->get_browser();
foreach($browser as $row)
{
$data['browser'] []= $row['browser'];
$data['percentage'] []= $row['data_percentage'];
}
header('content-type: application/json');
echo json_encode($data);
}
Models
function get_browser() {
$query = $this->db->select('browser, 100 / count(*) as data_percentage')
->from('tb_browser')
->group_by('browser')
->get();
return $query->result_array();
}
You should be dividing COUNT(*)
for each group by the total number of records in the table. For the latter quantity, you can use the following subquery:
SELECT COUNT(*) FROM tb_browser
Here is the full code:
function detail_metagenome_microbe_grafik($trflp_code, $metacode) {
$total = '(select count(*) from tb_browser)';
$query = $this->db->select('concat(round((100*count(*))/'.$total.',0),"%") as data_percentage')
->from('tb_browser')
->group_by('browser')
->get();
return $query->result_array();
}
Try this,
$query = $this->db->select('browser, (count(*) / <total_rec_count>) *100 as data_percentage')
->from('tb_browser')
->group_by('browser')
->get();
return $query->result_array();
need to get the actual total to do the calculation
$query = $this->db->select('browser, (count(*) / (select count(*) from tb_browser)) *100 as data_percentage')
I'm a bit rusty at mysql and haven't got an instance handy... unfortunately mysql doesn't support OVER()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.