|
|
Question : SQL Server Correlated sub query
|
|
|
|
I need to run a query that will run after an order is placed to update a TotalItems field to let us know the quantity of items ordered against a quota field. Ordered items can have an over ride price which hold the quota figure in a seperate table.
Products Table ID, Manufacturer, Model, Price 1, ManuA, ModelA, 50.00 2, ManuB, ModelB, 25.50 3, ManuC, ModelC, 14.65 4, ManuD, ModelD, 68.00
PriceOverRide Table ID, ProductsID, PartnerID, Price, Quota, TotalItems 1, 1, 12, 55.00, 200, 1 2, 4, 8, 69.00, 500, 0 3, 3, 12, 14.00, NULL, NULL
Partner Table ID, Name, Code, etc... 8, PartnerA, XXX, ... 12, PartnerB, XXX, ...
Only items that have an over ridden price will be entered in the PriceOverRide Table. So in the table above, Items ManuA, ManuC and ManuD have an overridden price (PriceOverride.Price) which is selected instead of Products.Price. If the quota is NULL then thats fine, we just dont have a quota on the item. If the TotalItems value (which will increase based on the orders placed) goes over the Quota figure then that item stops displaying the over ride price and reverts back to Products.Price. This all works fine.
To add to this, there is a Partner table. The partner ID is used in the PriceOverRide table to allow the override price to affect only a certain partner based on the PartnerID value rather than across the board.
The bit I need help with is when the order is placed I need to increment the PriceOverRide.TotalItems value by the number of items ordered only if they are in the PriceOverRide table and have a quota. So for example if my order contains 2 * ManuA ModelA items, 1 ManuC ModelC and 1 ManuD ModelD item then I would want the PriceOverRide Table to increment the TotalItems field by the number of items ordered.
Our PriceOverRide table then become:
ID, PriceID, PartnerID, Price, Quota, TotalItems 1, 1, 12, 55.00, 200, 3 2, 4, 8, 69.00, 500, 1 3, 3, 12, 14.00, NULL, NULL
I think this will be a Correlated sub query but just cant get it right. I'm not an expert on SQL but can get by.
|
|
|
|
Answer : SQL Server Correlated sub query
|
|
|
|
1:
2:
3:
4:
5:
6:
7:
|
update a
set a.Totalitems = case when a.Totalitems + b.quantity < a.quota or a.Quota is null then a.Totalitems + b.quantity else a.quota end
from PriceOverRide a
inner join Products c on a.ProductsId = c.ID
inner join orderdetails b on b.Manufacturer = c.Manufacturer and b.Model = c.Model
inner join Partner d on a.PartnerID = d.ID
where b.orderid = @yourcurrentorder
|
|
|
|
|
|