Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complicated Query

Tags:

People also ask

What is a complex query?

As the name suggests, a complex query has a complex syntax and can comprise multiple parts. A purpose of such a query is to search data based on several parameters. For instance, a complex query can include several joins across tables or have subqueries (a query nested within another query).

What is simple and complex queries?

Simple views can only contain a single base table. Complex views can be constructed on more than one base table. In particular, complex views can contain: join conditions, a group by clause, order by clause.

Is SQL complicated?

Generally speaking, SQL is an easy language to learn. If you understand programming and already know some other languages, you can learn SQL in a few weeks. If you're a beginner, completely new to programming, it can take longer.


I'm not sure if the following can be done using a mere select statement, but I have two tables (truncated with the data necessary to the problem).

Inventory Item

  • id int (PRIMARY)
  • quantity int

Stock - Contains changes in the stock of the inventory item (stock history)

  • id int (PRIMARY)
  • inventory_item_id int (FOREIGN KEY)
  • quantity int
  • created datetime

The quantity in stock is the change in stock, while the quantity in inventory item is the current quantity of that item

EVERYTHING IN THE running COLUMN WILL RETURN 0

SELECT
inventory_item.id,
(inventory_item.quantity - SUM(stock.quantity)) AS running
FROM
    stock
        JOIN
    inventory_item ON stock.inventory_item_id = inventory_item.id
GROUP BY inventory_item.id

THE QUESTION

Now, what I would like to know is: Is it possible to select all of the dates in the stock table where the running quantity of the inventory_item ever becomes zero using a SELECT?

I know this can be done programmatically by simply selecting all of the stock data in one item, and subtracting the stock quantity individually from the current inventory item quantity, which will get the quantity before the change in stock happened. Can I do this with a SELECT?