Summing up the price of production and selling prices - sql

I need to write query and calculate the total CostPrice’s and total Sellprice’s related to Material of ID=1. I want to calculate total costs so I have to include the QuantityColumn from the table Materials right?
SELECT SUM((CostPrice) * M.Quantity) AS 'TotalCostExclusive', SUM((SellPrice) * M.Quantity) AS 'SellPriceExclusive'
FROM Materials AS M INNER JOIN Warehouse AS W
ON M.Warehouse_id = W.Id
WHERE M.Material_Id = '1';
I tried this, but I'm not sure the result is equal to the required task.
Now I want to write new query to include the Discount on both cost and selling prices.
Since I’m a beginner and this data model is for student purpose, I would like to know why I must to have a table WarehouseIdentities. What exactly this table doing here and what role it has.

Related

Calculated field in a header table that sums values from a different table

I'm building a simple project database that holds data about foods and recipes. Recipes exist in the recipe header table that stores one row per recipe with basic overview and the recipe detail table stores rows for all ingredients that make up a recipe. What I want to achieve is a calculated column that shows the total number of calories per recipe.
I can get the total number of calories using the following query:
SELECT SUM(calories) FROM products pd
INNER JOIN recipe_detail rd ON pd.id = rd.product_id
WHERE rd.recipe_id = 1
This will get me the total calories for the first recipe. The problem is, I store the nutritional data in the products table for a specific number of grams (Usually 100g) whereas the recipe might need only 50g of a product. How do I adjust this query so that I would get a fraction of the calories I need?
I basically need to take the gram value of a product that belongs in a recipe, divide it by the gram value in the products table to get the ratio and then multiply that by the number of calories to get the answer.
Not sure about the names and types of your columns or how your information is stored exactly, but I think this might help:
SELECT r.*, SUM((p.calories * rd.weight) / p.weight::numeric) AS calories -- depending on the types of your columns, you can omit the cast; I added it to be sure it is not integer division
FROM recipe r
INNER JOIN recipe_detail rd ON rd.recipe_id = r.id
INNER JOIN porducts p ON p.id = rd.product_id
GROUP BY r.id

SQL : how to calculate an average from a query

I've been using SQL for about a week at my first full time job, and I'm trying to calculate some statistics from a query where I've combined columns from separate tables.
Specifically, I'm trying to calculate an average from a combined table, where I have applied filters (or constraints? I'm not clear on the SQL lingo).
From doing research on Google, I learned how to calculate an average:
SELECT AVG(column_name)
FROM table_name
The problem I'm having is that this only seems to work with existing tables in the database, not with new queries I have created.
A simplified version of my code is as follows:
SELECT
Animal_Facts.Animal_Name, Animal_Facts.Prev_Reg_Amount,
Names.Given_Name, Animal_Class.Class_Description
FROM
Names
INNER JOIN
Animal_Facts ON Names.Name_Key = Animal_Facts.Name_Key
INNER JOIN
Animal_Class ON Animal_Facts.Class_Key = Animal_Class.Class_Key
This query creates combines four columns from three tables, where Class_Description describes whether the animal is desexed, microchipped, owned by a pensioner etc, and Pre_Reg_Amount is the registration fee paid.
I want to find the average fee paid by pensioners, so I included the following line of code to filter the table:
AND Animal_Class.Class_Description LIKE ('%pensioner%')
And then to calculate the average I add:
SELECT AVG(Animal_Facts.Prev_Reg_Amount) from Animal_Facts
So my total code is:
SELECT
Animal_Facts.Animal_Name, Animal_Facts.Prev_Reg_Amount,
Names.Given_Name, Animal_Class.Class_Description
FROM
Names
INNER JOIN
Animal_Facts ON Names.Name_Key = Animal_Facts.Name_Key
INNER JOIN
Animal_Class ON Animal_Facts.Class_Key = Animal_Class.Class_Key
AND Animal_Class.Class_Description LIKE ('%pensioner%')
SELECT AVG(Animal_Facts.Prev_Reg_Amount)
FROM Animal_Facts
Now the problem is, after checking this calculation in Excel, I'm not actually getting the average of the pensioner data, but the average of all the data. Is there a way to calculate averages (and other statistics) directly from my created table in SQL?
Note: I am able to calculate all these statistics by exporting the data to Excel, but it is much more time consuming. I'd much rather learn how to do this within SQL.
SELECT AVG(af.Prev_Reg_Amount)
FROM
Animal_Facts af
INNER JOIN Animal_Class ac
ON af.Class_Key = ac.Class_Key
AND Class_Description LIKE ('%pensioner%')

How to calculate new value for field in Access

I've got a few problems with a database I have created.
I want to calculate a Total Price (Sandwich Quantity multiplied by Sandwich Price). I had it working before, but I had to delete Sandwich Price from the OrderDetailsT table of which it was originally in. I'm now having issues with this calculation, as I cannot make a calculation in the OrderDetailsT table (Sandwich Price isn't there).
How can I apply the Discount to the Total Price if the Total Price is more than $50 for instance? After the Discount has been applied to the Total Price field, I would also like to store it in the NewPriceAfterDiscount field.
Here is an image detailing my situation:
You have multiple questions in one:
But, first of all. As the image shows, why do you have a left join between OrderDetails an Sandwich? In a order calculation you don't need not ordered sandwiches.
To total price calculation:
Add a new column to the query grid (assuming discount is a percentaje stored has a number between 0 and 1):
[SandwichT].[SandwichPrice] * [OrderDetailT].[SandwichQuantity] * [OrderDetailT].[Discount]
To store total price: you can use the above formula, but using a update query.
If you plan to show the prices in a form or in a report:
you can do de calculations on the fly (and don't store the total
price)
or you should update the total price un one query and then build another
query as datasource of the form/report.
another posibility (my recomendation) is to store the total in the input form

How do I enforce, that the sum of a weight parameter equals 1, grouped by part of the key?

I have two tables in my setup. One with sales persons and there income. Each sales person only know their total income. For this particular income period, they are asked to give an estimate of their income on either private, small business or large business customers. This information is entered in the second table.
Income
=================
SalesPerson
Income
Distribution
=============================
SalesPerson
CustomerType
Weight
Now, my query would look something like this:
SELECT
Income.SalesPerson,
Distribution.CustomerType,
Income.Income * Distribution.Weight as DistributedIncome
FROM
Income INNER JOIN Distribution ON
Income.SalesPerson = Distribution.SalesPerson
How would I enforce, that the SUM(Weight) = 1 for each SalesPerson in Distribution?
Normalize by the sum, according to the same criteria.
SELECT
Income.SalesPerson,
Distribution.CustomerType,
Income.Income * Distribution.Weight/(
select sum(d.weight)
from distribution d
inner join income i on i.salesperson = d.salesperson
)
as DistributedIncome
FROM
Income INNER JOIN Distribution ON
Income.SalesPerson = Distribution.SalesPerson
If somehow want to select unmodified weights that sum to 1 then I believe you've got a case of the subset sum problem and you are probably not going to be able to solve this with an SQL query.

SQL joining, summing from sub queries to calculate a total aggregate amount

I've done all of this in active record, but it's not going to work with pagination so I'd like to switch to a SQL query with OFFSET so I can query efficiently. - Rather than getting User.all, then working out the calculations on related objects and then compiling it all into a bundled array and finally sending it up to the view I'd like to handle the calcs in a find_by_sql command so it's easier to manage pagination etc.
Trying to work out a users total amounts invested + their residual uninvented amounts in my little stock market simulator I'm playing with.
Have a share prices table that has multiple entries for each new share price for each company, so want to:
a) select the last entry from that table to get the latest share
price
b) ownerships shows what users from users table own what
company shares
c) So if we multiply shares_owned from the ownerships
table with the latest share price from a) then we get the total
amount invested
d) Once we have the total amount invested across all
companies, we need to add on what uninvested dollars the user has
associated with them so total invested + u.dollars should give us the
total valuation for a given user.
e) what screws me up is that a user might not own anything at a particular time, which means he will have no entries in the ownership table. In that case the query needs to only return his uninvested u.dollars amount.
Trying to get that total valuation per customer and order by 'richest' user:
select u.id,
sum(
((
select s.price from shareprices s
WHERE s.company_id = o.company_id and u.id = o.user_id
ORDER BY id DESC LIMIT 1) * o.shares_owned
))
+ u.dollars as totalAmount
from users as u full outer join ownerships as o on u.id = o.user_id group by u.id order by totalamount ASC
That returns fine for where there are ownerships and the calculations for total invested work out, but for users who only have uninvested dollars how can i get them to show in that summed column, so essentially its 0 (ie. no owned investment amounts because they own shares in no companies) + u.dollars to get how much they have, but I don't understand how to make SQL do that.
I am hoping to avoid needing a pgsql function() to achieve this logic but if the above didn't make it obvious, I'm terrible at SQL and only learning it now. I hope my explanation is even understandable!
You can add a colaesce around the part of the calculation that needs to treat nulls as zeros (its not clear to me which part needs to )
sum(COALESCE
((
select s.price from shareprices s
WHERE s.company_id = o.company_id and u.id = o.user_id
ORDER BY id DESC LIMIT 1) * o.shares_owned
)) , 0))
+ u.dollars totalAmount