SQL多重计算按顺序+舍入值

时间:2013-11-26 13:23:46

标签: sql sql-server sql-server-2008

我需要按顺序更新表格,以获得正确的最终结果。 但我认为当我执行以下语句时,它会同时运行所有计算,导致错误地计算结果。我需要的是得到这样的东西:

每日X O.F =订单

接下来

每日X(O.F + MCT +过境+安全)/货柜尺寸=看板卡数目

例如3.0的“看板卡号”的结果为4

接下来

O.F X每日/集装箱尺寸=运行线

Roundup,例如3.0的“Run Line”结果变为4

接下来

运行X行容器大小=批量大小

接下来

没有。看板卡X集装箱尺寸=最大库存

接下来

(KanBan卡号 - 运行线)X容器尺寸=触发器1

接下来

(KanBan卡号 - 运行线 - 1)X容器尺寸=触发器2

接下来

(KanBan卡号 - 运行线 - 2)X容器尺寸=触发器3

最后

每日X(0.5 X(O.F + MCT)+过境+安全)=平均库存

SELECT [Part Num], Daily, [O.F], [Order], MCT, Transit, [Safety], [Container Size], [No. of Kanban Card], [Run Line], [Lot Size], [Max. Inventory], [Trigger 1], [Trigger 2], [Trigger 3], [Avg. Inventory],
(Daily * [O.F]) AS [Order],
(Daily * ([O.F] + MCT + Transit + [Safety]) / [Container Size]) AS [No. of Kanban Card],
([O.F] * Daily / [Container Size]) AS [Run Line],
([Run Line] * [Container Size]) AS [Lot Size],
([No. of Kanban Card] * [Container Size]) AS [Max. Inventory],
(([No. of Kanban Card] - [Run Line]) * [Container Size]) AS [Trigger 1],
(([No. of Kanban Card] - [Run Line] - 1) * [Container Size]) AS [Trigger 2],
(([No. of Kanban Card] - [Run Line] - 2) * [Container Size]) AS [Trigger 3],
(Daily * (0.5 * ([O.F] + MCT) + Transit + [Safety])) AS [Avg. Inventory]
FROM SuperMarketTest

1 个答案:

答案 0 :(得分:0)

您可以选择每个计算作为子查询(或者更可读地作为公用表表达式),然后将下一个计算基于子查询或先前的CTE。

另一个可能更容易的选择是将所有计算作为多个更新语句,一个接一个地进行。

以下是CTE的一个例子......

;WITH c1 AS (
SELECT 
  [Part Num], 
  Daily, 
  [O.F], 
  [Order], 
  MCT, 
  Transit, 
  [Safety], 
  [Container Size], 
  [No. of Kanban Card], 
  [Run Line], 
  [Lot Size], 
  [Max. Inventory], 
  [Trigger 1], 
  [Trigger 2], 
  [Trigger 3], 
  [Avg. Inventory]
FROM SuperMarketTest
), c2 AS
(
SELECT 
  [Part Num], 
  Daily, 
  [O.F], 
  (Daily * [O.F]) AS [Order], 
  MCT, 
  Transit, 
  [Safety], 
  [Container Size], 
  (Daily * ([O.F] + MCT + Transit + [Safety]) / [Container Size]) AS [No. of Kanban Card], 
  [Run Line], 
  [Lot Size], 
  [Max. Inventory], 
  [Trigger 1], 
  [Trigger 2], 
  [Trigger 3], 
  [Avg. Inventory]
FROM c1
) , c3 AS
(
SELECT 
  [Part Num], 
  Daily, 
  [O.F], 
  [Order], 
  MCT, 
  Transit, 
  [Safety], 
  [Container Size], 
  [No. of Kanban Card], 
  ([O.F] * Daily / [Container Size]) AS [Run Line], 
  [Lot Size], 
  ([No. of Kanban Card] * [Container Size]) AS [Max. Inventory] 
  [Trigger 1], 
  [Trigger 2], 
  [Trigger 3], 
  [Avg. Inventory]
FROM c2
)
SELECT
  [Part Num], 
  Daily, 
  [O.F], 
  [Order], 
  MCT, 
  Transit, 
  [Safety], 
  [Container Size], 
  [No. of Kanban Card], 
  [Run Line], 
  [Lot Size], 
  [Max. Inventory] 
  (([No. of Kanban Card] - [Run Line]) * [Container Size]) AS [Trigger 1],
  (([No. of Kanban Card] - [Run Line] - 1) * [Container Size]) AS [Trigger 2],
  (([No. of Kanban Card] - [Run Line] - 2) * [Container Size]) AS [Trigger 3],
  (Daily * (0.5 * ([O.F] + MCT) + Transit + [Safety])) AS [Avg. Inventory]
FROM c3