0

我想从两个表中返回份额百分比计算的摘要结果,但我不知道如何执行此操作。我的表如下:

餐桌_

---+-----------+---------+-----------+---------+-----------+---------+----------+
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 递归地进行计算?

4

2 回答 2

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.

于 2013-02-21T04:09:53.050 回答
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

SqlFiddle 演示

于 2013-02-21T04:23:35.507 回答