Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL query to find values based on selected date, but will find the latest value if there's no value on the selected date
    primarykey
    data
    text
    <p>I want to get the branch values of the current date, but if there's no value for the current date, get the value of its latest reading. </p> <p>For example, the selected date is September 29, 2013.</p> <p>I have three branches.</p> <p>Two of those branches has sales value for September 29, 2013.</p> <p>One branch does not have encoded values, but this branch has a latest value date August 30, 2013.</p> <p>In other words,</p> <pre><code>Branch 1 - Sep 29 - value is 150 Branch 2 - Sep 29 - value is 150 Branch 3 - Sep 29 - value is 0 </code></pre> <p>I cannot just do 150 + 150 + 0 = 300</p> <p>What I have to do is:</p> <pre><code>Branch 1 - Sep 29 - value is 150 Branch 2 - Sep 29 - value is 150 Branch 3 - Sep 29 - value is 0, so find the latest reading, system finds August 30 with value 250. </code></pre> <p>So now I can do 150 + 150 + 250 = 550</p> <p>Currently, I have the following SQL query:</p> <pre><code>SELECT user_id, product_code, uom, inventory_date, account_id, branch_id, beginning_inventory FROM inventory_mgmt_uploads WHERE user_id = '137' AND product_code = 'GRO_AL' AND uom = 'box' AND account_id = '3' AND inventory_date &lt;= '2013-09-29' ORDER BY inventory_date </code></pre> <p>The result of the query above is:</p> <p><img src="https://i.stack.imgur.com/YFsQB.jpg" alt="enter image description here"></p> <p>Now what I want to achieve is this result:</p> <p><img src="https://i.stack.imgur.com/GsQqr.jpg" alt="enter image description here"></p> <p>What I've tried is this query:</p> <pre><code>SELECT user_id, product_code, uom, inventory_date, account_id, branch_id, beginning_inventory FROM inventory_mgmt_uploads WHERE user_id = '137' AND product_code = 'GRO_AL' AND uom = 'box' AND account_id = '3' AND inventory_date &lt;= '2013-09-29' GROUP BY branch_id ORDER BY inventory_date </code></pre> <p>But it gives me:</p> <p><img src="https://i.stack.imgur.com/Lr2Rq.jpg" alt="enter image description here"></p> <p>Even if I tried to do an order by branch_id desc, or inventory_date desc, I still can't get my desired output. Any ideas what will be the correct query? TIA!</p>
    singulars
    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.
 

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