SQL: Base Quantity that changes with demand and usage - mysql

I'm trying to build a view that calculates the potential material quantities for my company. I'm doing this code in Microsoft SQL Server 2008.
In the view we have a Material Number, a date, demand quantity, received quantity, and an initial quantity.
I have a date listed for when the item demand is needed, and when items are expected to be received. On each listed date, I'd like to know what our inventory will look like for each item. In my head I have determined what I need is the following:
CurrentOnHand - DemandQuantity + ReceivedQuantity = NewTotal
The new total will move down to the next row and will take the spot of the CurrentOnHand, and the calculation will be performed for each date on the item.
How would I go about achieving this? Do I need to make some sort of running total? Any help would be greatly appreciated. Thank you for taking the time!
Corey Hall

Related

Can I replicate this equation in excel through subqueries? I started differentiating between purchases and sales but now I'm stuck

just started learning sql last week and am trying to use a table imported using .csv to then carry out functions and add columns in the final table that perform these equations.
I am tasked with the first equation which is Taking the ((Purchases - Shares)/ (Purchases + sales), for a given owner, for a given year.
I have started a query that asks to look at transcode column and identify if it is P for Purchase, S for Sale and then from there I want to look at the shares column to then take that amount and plug it into the equation.
I am unsure if what I am trying to do is feasible?
Should I break it down further into seperate tables for purchases and shares?
Thank you.
[Picture of My data table labeled IHD in MySQL workebnch]
[MySQL Workbench to give you idea of code I wrote to distinguish Sales from purchases]
You can try something like :
select sum(shares) as num_of_shares , transcode, owner, YEAR(year) from table group by owner, transcode, YEAR(year)
This should give you aggregate of number of shares for sales and purchase per owner per year. After you can plug in this information into other queries to get the desired result.

How can I update inventory based on products listed in a Bill of Materials

I want to create an stored procedure to 'issue raw materials' from inventory into production.
In plain English I want to prompt the user to enter a ProductID, then pull up the Bill of Materials for the specified ProductID, then subtract the components listed in the BOM from Inventory. (I understand how to update a single item, but I'm wondering if there is a way to update multiple inventory records at once based on the parts that are listed in the BOM)
This is what I have so far. https://i.stack.imgur.com/FTAAL.png (Please click image link)
I want to take the quantity of components requried to build ProductID 794, and subtract them from the Inventory.
I'm new to SQL, and playing around with the AdventureWorks2012 database. Any help is very much appreciated!
Thanks!

How do I use lag/lead to project opening/closing inventory over time in RedShift?

I have a query that would give me the opening stock for today, expected sales and purchases for the next few days (where there is no value for either, a null value is returned. What I would like to get to is to project the upcoming opening stock. How can I do this?
My current query would look very much like this in RedShift:
select date,opening_stock,sales,purchases
from inventoryandforecast
Current Output
I imagine that to accomplish the following output, I need to calculate a closing inventory for each day (where closing inventory = starting inventory - sales + purchases) and use either lag/lead for the opening inventory the next day, but I fail to understand how to do this. What should my query look like?
Intended output
Thank you for your time.

Architecture: Ordering in Rails or MySQL

I have an AngularJS front-end app that sends requests to a Rails API back-end. When a user search for items, so far the query is limited to 20 elements and is always ordered by popularity (a field stored in database). After the results are retrieved from DB, there is a complex process that calculates the item prices iterating one by one (remember only 20 elements). After that, the results are served to the user. Note: As told, item prices cannot be calculated directly in the query because an item can have different prices according to dates and also discounts can be applied.
This is how it´s working so far.
Now, I would like to introduce in the search results page an innocent order by: Price functionality. So, the array of items should come ordered by price.
As, I can´t get the prices directly with just one query, I see two choices:
To keep it as it is right now, I mean, making the query ordered by popularity and order the results after the prices are calculated. But I see a problem, If I get 20 elements each time ordered by popularity, then I can calculate prices and order by price these 20 elements, so I assume I´m not ordering correctly by price. This case, I would need to query without limit, to get all items, calculate prices, order them by price and return to user. I think I would also to develop a home-made pagination functionality.
Develop some kind of stored procedure in the database to provide the results with the complex prices calculations. I don´t know if I can order them easily. I´m worried because I don´t know stored procedures in MySQL and not sure if it´s possible to do what I need.
But, from the performance point of view, I guess the second choice should be better, right? I´d appreciate comments or any other options?
UPDATE:
According to comments, I detail how to calculate prices functionality.
A user can rent an item for many days (a week i.e.). So, there is a check-in and check-out dates.
Also, prices changes according to seasons. This means days can have different prices in a selected week. So, in order to calculate the total price, you have to get the daily price matching each selected day in the week and add it to the total price.
Once, the base price is calculated, there can be discounts. Same as prices, discounts can be applied only for some days, so first, it must be checked if there is any discount for the selected week. If so, the discount is applied to base price to get the total final price.
Please, let me know if you need the code.
This should be done on the backend (MySQL).
Like you mentioned, if you want to sort by price on the front-end, you'll have to replicate the entire database into Angular. Which is probably a bad idea.
This is the approach I would take in MySQL:
Set up a table with item_id, date, and price (or perform the joins necessary to get this table).
Apply discounts for each date. This step yields an interim table with updated prices.
Build your final query. Your SELECT clause should SUM(price). You should GROUP BY item_id. And you should ORDER BY SUM(price) DESC.
Depending on the size of your database, this query may require a lot of fine-tuning in order to return results quickly. But it definitely can (and should) be done in the backend.
Good luck!
EDIT: With a really big set of items, running this query through MySQL may become too slow, regardless of how much time you spend tuning performance. If MySQL doesn't cut it, you may need to rely on an auxiliary database like Elasticsearch.
But before turning to Elasticsearch/Hadoop/etc, you should think carefully about how "complex" your pricing algorithm really is. In all likelihood you can optimize the MySQL query to the point where it performs just fine.
This is a classical search listing problem. If you want to perform sort based on price, obviously you need the required inputs. it is worth mentioning that stored procedure won't magically improve the performance. The best what you can do is run recurring CRON job every hour/day ( bonus tip : use upset and perform mass operation) which updates the price. Now perform join and do the query and order it with "price". Also make sure to put indexes on required fields. After grabbing the result apply discount and show the result. If query is complex the pagination won't work. You have to do all sorts of operation manually. If you are using will_paginate , it has some function which also support Array instead of active record. Hope this helps.
So you have the following factors then:
User Inputs Beginning Date, End Date and sees list of items.
The Beginning - End Date period (selected period) is consistent for all items in the query.
To sort by price you must, for each item in the table (not just those retrieved)
Get Item Price for each day of the selected period.
Get available discounts for each day of the selected period.
Calculate Total Price for selected period.
Because user input is involved you will not be able to definitively calculate this and store the final product. The best you could do is calculate the gross and net prices per day and cache that, then performing the final calculation based on user input (or sending that data to browser for calculation there)
You could also use a first order approximation and just go with the current gross value, and then tweak from there. That assumes that the relationship between item prices remains more or less consistent.

Add row data to total,without showing row values SSRS

I am relatively new to SSRS. This is a Dynamics CRM report. My scenario is that I have a 15 truck drivers. I have created a report that shows their number of trips and the miles driven. I can sum the miles and get the total number of miles for each driver.
What I want is just the driver name and the total number of miles driven.I am not sure how to get that calculation done in SSRS. Any help would be greatly appreciated.
Regards
SR
It will be straight forward if your dataset just returns the data you need - the driver name and the total numbers.
But if your dataset returns the detailed data, not totals, then you can just hide the detail row of the tablix: right click on the detail row header -> Row Visibility... -> select the "Hidden" radio button. With that, I'm assuming your report already has the grouping by Driver and shows the total miles.
Best regards,
~Alexey