我正在使用自我加入来获取年初至今的总数。这有效:
SELECT tc.EmployeeID, tc.TimeCardNum, tc.Tax, SUM(inr.Tax) AS YTDTax
FROM TimeCards tc
JOIN (
SELECT EmployeeID, TimeCardNum, Tax
FROM TimeCards
) AS inr
ON inr.EmployeeID = tc.EmployeeID
AND inr.TimeCardNum <= tc.TimeCardNum
GROUP BY tc.EmployeeID, tc.TimeCardNum, tc.Tax
ORDER BY tc.EmployeeID, tc.TimeCardNum
这为我提供了一个可以为每位员工重置的运行总计列。
现在我想将其转换为UPDATE
查询以将该数据放入新列中。这是怎么做到的?
答案 0 :(得分:2)
你试过了吗?
UPDATE a
SET a.YTDTax=b.YTDTax
FROM TimeCards a
INNER JOIN (
SELECT tc.EmployeeID, tc.TimeCardNum, tc.Tax, SUM(inr.Tax) AS YTDTax
FROM TimeCards tc
JOIN (
SELECT EmployeeID, TimeCardNum, Tax
FROM TimeCards
) AS inr
ON inr.EmployeeID = tc.EmployeeID
AND inr.TimeCardNum <= tc.TimeCardNum
GROUP BY tc.EmployeeID, tc.TimeCardNum, tc.Tax
) b on a.EmployeeID=b.EmployeeID
AND a.TimeCardNum = b.TimeCardNum
在事务中运行以确保它产生所需的输出。