我想从两个表中返回份额百分比计算的摘要结果,但我不知道如何执行此操作。我的表如下:
餐桌_
---+-----------+---------+-----------+---------+-----------+---------+----------+
id | product_1 | share_1 | product_2 | share_2 | product_3 | share_3 | amount |
---+-----------+---------+-----------+---------+-----------+---------+----------+
1 | 3 | 50 | 2 | 50 | | | 5000 |
2 | 2 | 50 | 1 | 25 | 4 | 25 | 10000 |
3 | 5 | 50 | 4 | 50 | | | 7000 |
---+-----------+---------+-----------+---------+-----------+---------+----------+
餐桌用品
---+-----------+
id | name |
---+-----------+
1 | Book |
2 | Pen |
3 | Ruler |
4 | Pencil |
5 | Calendar |
---+-----------+
我希望结果是这样的:
Product_name | Total
-------------+----------
Book | 2500
Pen | 7500
Ruler | 2500
Pencil | 6000
Calendar | 3500
-------------+----------
Grand Total | 22000
到目前为止,我已经尝试过这个查询
$this->db->select('t1.name as product_name, sum(t2.amount) as total');
$this->db->from('products t1');
$this->db->join('pa t2', 't2.product_1 = t1.id OR t2.product_2 = t1.id OR t2.product_3 = t1.id', 'left');
$this->db->group_by('t1.name');
$query = $this->db->get();
SQL 小提琴:http ://sqlfiddle.com/#!2/471c4/1
但它没有返回我想要的结果,因为没有计算每个产品的份额百分比。
有没有办法只用 SQL 查询返回我想要的结果?还是我必须用 PHP 递归地进行计算?