2012-11-08 30 views
0

我想創建一個查詢,這將允許我將多個行分割一個數字。SQL查詢分割運輸成本在多個項目/行

例如,採購訂單x可能有15個項目分配給它。運費是9.95美元。我如何計算9.95的1/15,然後以1/15的運輸成本更新股票的成本價格?

因此,該項目的成本價格將從4.50增加到5.16(4.50 + 0.66)。

+0

您能提供一個示例表,您可能使用它來保存此數據嗎? – PinnyM

+0

在這裏你去... [採購訂單] POID,客戶ID,PODate,供應商 [POStock]鏈路ID,PONO,StockCode,進價 我想和交付成本的比重來更新購買價格。 – alcomcomputing

+0

你使用的是什麼rdbms? SQL服務器,甲骨文,MySQL的? – Taryn

回答

0

我已經創建了產品表並更新了物品的​​運費。 希望這就是你要找的。

INSERT INTO [TravelAgentDB].[dbo].[Product] 
      ([ID] 
      ,[Name] 
      ,[Price] 
      ,[shippingPrice]) 
    VALUES 
      (1,'Nexus 7' , 250 , 20), 
      (2,'Nexus 7 case' , 50 , 20), 
      (3,'Nexus 7 headphone' , 20 , 20) 
GO 


select * from product 
Declare @itemsCount int 
Select @itemsCount = count(*) From product where id in (1,2,3) 
Declare @totalShippingPrice Decimal(18,2) = 9.95 
Declare @shippingPriceperItem Decimal(18,2) = @totalShippingPrice/@itemsCount 

Update Product 
set [shippingPrice] = @shippingPriceperItem 
Where id in (1,2,3) 
select * from product 
+0

感謝Sayed,我已將它精簡爲一條SQL語句如下: UPDATE [STOCK - DETAIL]設置CostPrice = CostPrice + round((9.00 /(從STOCK - DETAIL中選擇count(*))PONo = 2971 )),2)其中PONo = 2971 – alcomcomputing

2

下面是SQL Server的一個解決方案:

update ol 
set  price = price + 5.0/ol.LineCount 
from [Order] o 
join (
     select * 
     ,  count(*) over() as LineCount 
     from OrderLine 
     ) ol 
on  o.ID = ol.OrderID 
where o.OrderNr = 'Ord1'; 

Live example at SQL Fiddle.

如果你使用其他DBMS,請更新您的文章!