Php codeigniter:按数据类别获取多个表中的百分比
我有这样的桌子Php codeigniter:按数据类别获取多个表中的百分比,php,mysql,codeigniter,model,Php,Mysql,Codeigniter,Model,我有这样的桌子 table_a PID Name Type 1 a selling 2 b sampling 3 c selling 4 d sampling 5 e selling output_selling Name Total_qty Percentage a 4 40% c 3
table_a
PID Name Type
1 a selling
2 b sampling
3 c selling
4 d sampling
5 e selling
output_selling
Name Total_qty Percentage
a 4 40%
c 3 30%
e 3 30%
以及
我需要像这样展示
table_a
PID Name Type
1 a selling
2 b sampling
3 c selling
4 d sampling
5 e selling
output_selling
Name Total_qty Percentage
a 4 40%
c 3 30%
e 3 30%
以及
我如何在CodeIgniter中实现这一点?您可以在函数中使用下面的内容,并根据需要更改“采样”和“销售”:
$this->db->query("
SELECT dd.NAME,
dd.total_qty,
( dd.total_qty / dd.totals ) * 100 AS Percentage
FROM (SELECT a.NAME,
Sum(b.qty) AS Total_qty,
(SELECT Sum(b1.qty) AS total
FROM table_b b1
JOIN table_a a1
ON a1.pid = b1.pid
AND a1.type = 'selling') AS totals
FROM table_a a
JOIN table_b b
ON b.pid = a.pid
AND a.type = 'selling'
GROUP BY a.pid) dd ");
请参见以下查询输出:
函数输出\u selling(){$total=$this->db->select('SUM(table_b.Qty)as total_Qty',FALSE);$this->db->from('table_b');join('table_a','table_a.PID=table_b.PID',left');$this->db->where('table_a.Type','selling');$this->db->group_by('table_b.PID');$query=$this->db->get();return$query->result();}