我需要在計算重量和成本的基礎上創建一份報告。其他事情我已經做了,但如何計算成本是我所缺少的,我沒有得到任何想法來實作這一點。 誰能建議一下如何實作這個輸出。
以下是測驗資料。
Create table #temp
(
ID int,
StopNumber int,
[重量] int,
成本 decimal (18,2)。
類別 nvarchar(max)
)
插入 into #temp values (1, 1,5719,3099, 'Linehaul')
插入 into #temp values (1, 2,2627, 393. 82,'Fuel')
插入 into #temp values (1, 3,3096,215,'附件')
插入 into #temp values (2, 1,6000,4500, 'Linehaul')
插入 into #temp values (2, 2,5000, 383. 82,'Fuel')
插入 into #temp values (2, 3,4000,315,'Accessorial')
select * from #temp
ID 停止編號 重量 成本類別
1 1 5719 3099.00 Linehaul
1 2 2627 393.82燃油
1 3 3096 215.00 附加條件
2 1 6000 4500.00 Linehaul
2 2 5000 383.82燃油
2 3 4000 315.00 附加物
預期輸出
ID StopNumber Weight Cost Category LineHaul Fuel Accessorial
1 1 5719 3099. 00 Linehaul 1,548.96 196.84 107.46.
1 2 2627 393. 82燃料711.51 90.42 49.36
1 3 3096 215. 00 附加費838.53 106.56 58.18
2 1 6000 4500. 00 Linehaul 1,800.00 153.53 126
2 2 5000 383. 82燃料1,500.00 128 105
2 3 4000 315. 00 附加費1,200.00 102.35 84.
需要根據重量百分比來計算線路運輸、燃料和附件的費用。
例如:ID 1的重量之和=11442 ID 2的重量之和=15000
現在5719/11442=50%ID 1的線上總成本=3099
因此,線路運輸成本=215
因此,線路運輸成本將根據百分比計算分配給3個權重
3099 * 50 % = 1548.963099 * 23 % = 711.51
同樣的計算方法也將用于燃料和附件費用,并用于不同的ID。
uj5u.com熱心網友回復:
使用視窗函式與sum()集合。
對于按ID計算的總重量
sum([Weight]) over (partition by ID) `
類似地,你可以使用CASE運算式與視窗函式來查找一個ID的類別的成本,例如Linehaul
sum(case when Category = 'Linehaul' then [ Cost] end) over (partition by ID)
select *,
Linehaul = [Weight] * 1。 0 / sum([Weight]) over (partitionby ID)
* sum(case when Category = 'Linehaul' then [ Cost] end) over (partition by ID) 。
燃料 = [重量] * 1. 0 / sum([Weight]) over (partitionby ID)
* sum(case when Category = 'Fuel' then [ Cost] end) over (partition by ID) 。
Accessorial = [Weight] * 1. 0 / sum([Weight]) over (partitionby ID)
* sum(case when Category = 'Accessorial' then [ Cost] end) over (partition by ID)
from #temp t
order by ID, StopNumber
uj5u.com熱心網友回復:
你可以使用視窗函式來計算每個id的總數。 剩下的只是算術。 如果我按照你的邏輯正確的話:
select t.*。
(weight / id_linehaul) * (cost) aslinehaul,
(重量/ id_fuel) * (成本) 作為燃料。
(重量 / id_accessorial) * (cost) as accessorial
from (select t.*,
sum(weight) over (partition byid) as id_weight,
sum(case when categories = 'Linehaul' then cost end) over (partition by id) as id_linehaul,
sum(case when categories = 'Fuel' then cost end) over (partition by id) as id_fuel,
sum(case when categories = 'Accessorial' thencost end) over (partition byid) as id_accessorial
from t
) t
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334020.html
標籤:
