因此,以下Windows函数可以获取计算列:
USE MfgMetrics
SELECT
[Calc_ORDER_NUMBER_LAG] = LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate]),
[Calc_Order_Quantity_LAG] = LAG([Order_Quantity],1,0) OVER (Order By [ORDER NUMBER], [FileDate]),
[Calc_Qty_Changed] =
(
CASE
WHEN [ORDER NUMBER]!=LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate]) THEN 2
WHEN [ORDER NUMBER]=LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate])
AND [ORDER NUMBER]!=LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate])
AND [Order_Quantity] != LAG([Order_Quantity],1,0) OVER (Order By [ORDER NUMBER], [FileDate])
AND [ACTUAL START DATE] != 0 AND [FileDate] >= [ACTUAL START DATE]
THEN 1
ELSE 0
END
)
FROM dbo.Testing_Table_II
但是我需要将计算的列添加到Testing_Table_II,当我尝试这个时:
USE MfgMetrics
ALTER TABLE dbo.Testing_Table_II
SELECT
ADD [Calc_ORDER_NUMBER_LAG] AS LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate]),
ADD [Calc_Order_Quantity_LAG] AS LAG([Order_Quantity],1,0) OVER (Order By [ORDER NUMBER], [FileDate]),
ADD [Calc_Qty_Changed] AS
(
CASE
WHEN [ORDER NUMBER]!=LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate]) THEN 2
WHEN [ORDER NUMBER]=LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate])
AND [ORDER NUMBER]!=LAG([ORDER NUMBER],1,0) OVER (Order By [ORDER NUMBER],[FileDate])
AND [Order_Quantity] != LAG([Order_Quantity],1,0) OVER (Order By [ORDER NUMBER], [FileDate])
AND [ACTUAL START DATE] != 0 AND [FileDate] >= [ACTUAL START DATE]
THEN 1
ELSE 0
END
)
FROM dbo.Testing_Table_II
它不起作用...当Windows函数必须在SELECT FROM中时,我不确定如何进行alter或create列。
任何帮助表示赞赏!我对这些东西真的很陌生,所以我可能会感到很小(愚蠢)。提前谢谢!
答案 0 :(得分:2)
您需要先更改表格,然后将选择作为更新运行,并加入字段键。
ALTER Testing_Table_II ADD
Calc_ORDER_NUMBER_LAG AS INT,
Calc_Order_Quantity_LAG AS INT,
Calc_Qty_Changed AS INT
GO
UPDATE
TT
SET
TT.Calc_ORDER_NUMBER_LAG= TT2.Calc_ORDER_NUMBER_LAG,
TT.Calc_Order_Quantity_LAG= TT2.Calc_Order_Quantity_LAG
...
FROM
Testing_Table_II AS TT
INNER JOIN
(
<PASTE YOUR FIRST QUERY HERE>
)
AS TT2 ON TT.PrimaryKey = TT2.PrimaryKey