Average column values and show the output in another column - sql

I have some products in a table tbProduct which has these columns:
Pcode
product
Avg_costprice
And I have another table which its name is tbStockIn and it has these columns:
Pcode
Product
Cost-price
How can I take the average of the column Cost-price according to Pcode, and show the output in the column Avg_costprice?
Please help me.

If you want to update Avg_costprice of tbProduct related to tbStockIn use this code:
UPDATE tbProduct SET
Avg_costprice = (SELECT AVG(Cost-price) FROM tbStockIn
WHERE tbStockIn.Pcode = tbProduct.Pcode)
I hope it helps you with your purpose.

I can see 3 options.
A. Don't have tbProduct
It seems like you may not need tbProduct and you could just ask for Avg_costprice when you need it:
SELECT
Pcode,
AVG(Cost-price) AS Avg_costprice
FROM tbStockIn;
B. Update tbProduct every time tbStockIn changes
If you have to have tbProduct then every time you interact with tbStockIn you'll need to update the average price. Upon a change to tbStockIn you can:
update the avg. prices only for the products you modify,
recalculate the avg-prices for the whole product table.
C. Computed column
Please see formula for computed column based on different table's column.

Related

SQL Trigger On Different Tables

I have a Database that looks like this.
Whenever a new user is created, the Id of the User(UserName) needs to be stored in the Budget table. After this, I want the attribute category in the Budget table to be filled with every category in the Category table.
My current Category table:
As you can see, I currently have 3 categories. Is it possible to create a Trigger which loops trough the categories, and inserts the Category.Id into Budget.Category.
The Budget table should look like this after a user has been created:
I don't know how to add each categoryId to the Budget table.
To insert the values into the budget table, the code would look something like this:
insert into budget(UserId, CategoryId, Date, Value)
select new.userid, c.categoryId, current date, 0
from categories c;
No foreach is required, but the syntax varies by database. In particular:
The syntax for the current date.
The syntax for accessing the values being inserted.

How do I show a field count in another table?

I am new to SQL and trying to learn by doing some beginner exercises. I'm working in Visual Studio.
I have one table with some Theater shows including Receipt ID, SeatRow and SeatNumbers.
I have another table consisting of Phone Numbers, Receipt IDs and TheatherShow IDs.
Now I want to make a third table showing how many seats are tied to each Receipt ID.
I've been trying to do this:
Update Table_Seat_Count
set Seat_Count = Count(Seat_Number) FROM Plads
WHERE ReceiptID = ReceiptID
Setting the Seat_Count equal to the number of seats where the ReceiptID is the same within the two tables.
Hope you can help me, thanks in advance.
You need a sub-select:
Update Table_Seat_Count
set Seat_Count = (select Count(Seat_Number) FROM Plads
WHERE Plads.ReceiptID = Table_Seat_Count.ReceiptID)
But in general it's a good idea to never store computed values. (If Plads is updated, and Table_Seat_Count isn't you've got inconsistent data...) Views are great, with them you'll always have consistent data!

can't make a trigger update only the relevant rows

I'm working on a school project and my trigger gives me a hard time.
Its' purpose is to update the Rating field of an updated Product, but it updates all rows in Products instead.
CREATE TRIGGER Update_Rating
ON dbo.Reviews
FOR Insert
as
Update dbo.Products
set Rating=(Select [avarage_rating]=avg(r.Rating)
From dbo.Reviews as r join inserted on r.ItemNumber = inserted.ItemNumber
where r.ItemNumber = Inserted.ItemNumber)
Your help is much appreciated
What you are trying to do is calculate the average of a column, which is a number. There will not be a unique average per row. Hence the Rating column in your desired table gets updated with this value. Try changing your update condition and it should work.

SQL trigger updating table using another table

Hi everyone I am still sort of new to SQL, I have a slight problem and maybe someone can help.
I have researched all about triggers and what I read make sense, but I can't get the answer I need from it for some reason so I will explain what I need to do
I have 2 tables Products, LabelPrint
In products there are 5 columns upc, itemcode, description, price, labelprint
In LabelPrint there are the same columns
What I need is a trigger for when a new item is created or a old item is edited and the column LabelPrint is modified to =1 for yes
I need the item in question to be copied over to labelprint table
The label print table is automatically cleaned of this items after a certain period of time, I just hope someone can give me some help in understanding how I can make this trigger work the way I hope it will
thanks brandon
I would try something like this:
CREATE TRIGGER InsertProducts
ON dbo.Products
FOR INSERT
AS
INSERT INTO dbo.LabelPrint(upc, itemcode, description, price, labelprint)
SELECT
upc, itemcode, description, price, labelprint
FROM Inserted
WHERE labelprint = 1
This first trigger will fire whenever you insert data into the table dbo.Products, and if the labelprint column is set to 1, then those rows are inserted into dbo.LabelPrint as well.
The UPDATE is a bit trickier:
CREATE TRIGGER UpdateProducts
ON dbo.Products
FOR UPDATE
AS
INSERT INTO dbo.LabelPrint(upc, itemcode, description, price, labelprint)
SELECT
i.upc, i.itemcode, i.description, i.price, i.labelprint
FROM Inserted i
INNER JOIN Deleted d ON i.itemcode = d.itemcode
WHERE i.labelprint = 1 AND d.labelprint <> 1
Here, I check to see that the row has been updated (not 100% sure if itemcode is the best column to use to link the old and new values - adapt as needed if it's not), and I make sure the old value (from the Deleted pseudo-table) is not 1 while the new value (from Inserted) is 1 - in that case, the column LabelPrint has been updated to 1 and that row will be copied into the LabelPrint table.
One word of caution: you need to be aware that SQL Server does not fire the trigger for each row that is being inserted and/or updated. The trigger will fire once for each statement - and that one statement could very well update 50 rows - in that case, the trigger fires once, and the pseudo-tables inside the trigger (Inserted, Deleted) will contain 50 rows each. Just don't ever assume that Inserted only ever contains a single row - that assumption would be totally false.

insert into table where if not in list

Can anybody help me with the syntax?
insert into history (company,partnumber,price)
values ('blah','IFS0090','0.00')
if company NOT IN ('blah','blah2','blah3','blah4','blah4')
and partnumber='IFS0090';
Background:
I have a history table which stores daily company, products and prices. But sometimes a company will remove itself for a few days. Complicating the issue is because I'm only saving daily CHANGES to prices only and not snapshotting the entire days list (the data would be huge) when I display the data the company will still come up for the previous days price. So I need to do something like this, where a 0.00 price means they're no longer there.
Use:
INSERT INTO HISTORY
(company, partnumber, price)
SELECT 'blah', 'IFS0090','0.00'
FROM HISTORY h
WHERE h.company NOT IN ('blah','blah2','blah3','blah4','blah4')
AND h.partnumber = 'IFS0090'
You are mixing two completely different concepts in your statement. Choose one:
Either you want to INSERT constant values (in that case make your checks in your programming language and generate the INSERT INTO ... VALUES (...) accordingly)
or insert the filtered contents of another table.
The latter is possible in MySQL (that's the INSERT ... SELECT syntax), the query would look like this:
INSERT INTO history (...)
SELECT ...
FROM liveTable
INNER JOIN moreTables ...
--# this is a regular SELECT statement, as you might have guessed by now
WHERE company NOT IN ('blah','blah2','blah3','blah4','blah4')
AND partnumber='IFS0090';