我想从两个表中返回共享百分比计算摘要的结果,但我不知道如何执行此操作。我的表格如下:
表 pa
---+-----------+---------+-----------+---------+-----------+---------+----------+
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递归计算?
答案 0 :(得分:0)
您可以先通过取消隐藏数据来进行计算:
select p.name, sum(amount)
from ((select product_1 as pid, amount*share_1 / 100.0 as amount from pa) union all
(select product_2 as pid, amount*share_2 / 100.0 as amount from pa) union all
(select product_3 as pid, amount*share_3 / 100.0 as amount from pa)
) pp join
product p
on pp.pid = p.id
group by p.name
您可以在应用程序中或使用ROLLUP
获取总数。
答案 1 :(得分:0)
尝试以下SQL:
SELECT product_name, SUM(percentage)
FROM
(
SELECT t1.name as product_name, t2.share_1, t2.amount, (t2.share_1*t2.amount)/100 as percentage
FROM products t1 JOIN pa t2 ON t2.product_1 = t1.id
GROUP BY t1.name
UNION
SELECT t1.name as product_name, t2.share_2, t2.amount, (t2.share_2*t2.amount)/100 as percentage
FROM products t1 JOIN pa t2 ON t2.product_2 = t1.id
GROUP BY t1.name
UNION
SELECT t1.name as product_name, t2.share_3, t2.amount, (t2.share_3*t2.amount)/100 as percentage
FROM products t1 JOIN pa t2 ON t2.product_3 = t1.id
GROUP BY t1.name
) as temp_table
GROUP BY product_name