使用聚合自联接更新查询

发布于 2024-11-07 22:24:07 字数 465 浏览 0 评论 0原文

我正在使用自连接来获取年初至今的总数。这有效:

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 查询以将该数据放入新列中。这是怎么做到的?

I am using a self-join to get year-to-date totals. This works:

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

which gives me a running total column that resets for each employee.

Now I want to turn it into an UPDATE query to put that data into a new column. How is this done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人间☆小暴躁 2024-11-14 22:24:07

您是否尝试过:

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

在事务中运行以确保它产生所需的输出。

Have you tried:

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

Run in a transaction to ensure it produces the desired output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文