Note that there are some explanatory texts on larger screens.

plurals
  1. PO3 joins and where clause together
    primarykey
    data
    text
    <p>I have 3 tables</p> <pre><code>bl_main (bl_id UNIQUE, bl_area) bl_details (bl_id UNIQUE, name) bl_data(bl_id, month, paper_tons, bottles_tons) </code></pre> <p><code>bl_id</code> is not unique in the last table. There will be multiple rows of same <code>bl_id</code>. </p> <p>I am trying to retrieve data in the following way</p> <pre><code>bl_id | name | bl_area | sum(paper_tons) | sum (bottles_tons) | paper_tons | bottles_tons </code></pre> <p><code>sum(paper_tons)</code> should return the sum of all the paper tons for the same <code>bl_id</code> like Jan to December.</p> <p>Using the below query i am able to retrieve all the data correctly except in the result, there are multiple occurances of <code>bl_ids(From bl_data table)</code>. </p> <pre><code>SELECT bl_main.bl_id,name,bl_area,sums.SummedPaper, sums.SummedBottles,paper_tons,bottles_tons FROM bl_main JOIN bl_details ON bl_main.bl_id= bl_details.bl_id left outer JOIN bl_data ON bl_data.bl_id= bl_main.bl_id left outer JOIN ( SELECT bl_id, SUM(Paper_tons) As SummedPaper, SUM(bottle_tons) As SummedBottles FROM bl_data </code></pre> <p>GROUP by bl_id) sums ON sums.bl_id = bl_main.bl_id</p> <p>I wanto retrieve only the unique values of bl_ids without repetition and it should contain the bl_id which has the max month and not all the months for the same bl_id. </p> <p>For ex: </p> <pre><code>INCORRECT **0601** University Hall 75.76 17051 1356 4040 1154 **11** **0601** University Hall 75.76 17051 1356 9190 101 **12** **0605** UIC Student 22.86 3331 14799 0 356 **8** CORRECT **0601** University Hall 75.76 17051 1356 9190 101 **12** **0605** UIC Student 22.86 3331 14799 0 356 **8** </code></pre> <p>I know I can get the max value using </p> <pre><code>WHERE Month = (SELECT MAX(Month) </code></pre> <p>but where exactlt should i add this in the query and should i change the join definition. Any help is highly appreciated as i am new to sql. Thanks in advance.</p>
    singulars
    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.
    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.
 

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