Note that there are some explanatory texts on larger screens.

plurals
  1. POSummary of a share percentage calculation from two tables
    primarykey
    data
    text
    <p>I want to return the result of summary of a share percentage calculation from two tables but I have no idea on how to do this. My table is as follows:</p> <p>table <strong>pa</strong></p> <pre><code>---+-----------+---------+-----------+---------+-----------+---------+----------+ 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 | ---+-----------+---------+-----------+---------+-----------+---------+----------+ </code></pre> <p>table <strong>products</strong></p> <pre><code>---+-----------+ id | name | ---+-----------+ 1 | Book | 2 | Pen | 3 | Ruler | 4 | Pencil | 5 | Calendar | ---+-----------+ </code></pre> <p>I want the result to came out like this:</p> <pre><code>Product_name | Total -------------+---------- Book | 2500 Pen | 7500 Ruler | 2500 Pencil | 6000 Calendar | 3500 -------------+---------- Grand Total | 22000 </code></pre> <p>As far, I've tried this query</p> <pre><code>$this-&gt;db-&gt;select('t1.name as product_name, sum(t2.amount) as total'); $this-&gt;db-&gt;from('products t1'); $this-&gt;db-&gt;join('pa t2', 't2.product_1 = t1.id OR t2.product_2 = t1.id OR t2.product_3 = t1.id', 'left'); $this-&gt;db-&gt;group_by('t1.name'); $query = $this-&gt;db-&gt;get(); </code></pre> <p>SQL Fiddle: <a href="http://sqlfiddle.com/#!2/471c4/1" rel="nofollow">http://sqlfiddle.com/#!2/471c4/1</a></p> <p>But it not returning the result I want since there's no calculation for the share percentage for each product.</p> <p>Is there any way to return the result I want with only SQL query? Or do I have to do the calculation recursively with PHP?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload