使用组的最大值更新列

发布于 2025-01-15 08:41:46 字数 1166 浏览 1 评论 0原文

在 SQL Server 中,让我们考虑这个表:

IdPartNumberTimestampReintegration
111112020-01-01NULL
211112020-01-02NULL
322222021-02-01NULL
422222021-02-02NULL

我想更新ReintegrationGroup By PartNumberMAX 值。

这是预期的结果:

IdPartNumberTimestampReintegration
111112020-01-01NULL
211112020-01-022020-01-02
322222021-02-01NULL
422222021-02-022021-02-02

我有使用GROUP BYMAXINNER JOIN尝试了很多东西,但没有成功。

感谢您的任何帮助。

In SQL Server, let's consider this table:

IdPartNumberTimestampReintegration
111112020-01-01NULL
211112020-01-02NULL
322222021-02-01NULL
422222021-02-02NULL

I want to update the Reintegration column with the MAX value of a Group By PartNumber.

Here is the expected result :

IdPartNumberTimestampReintegration
111112020-01-01NULL
211112020-01-022020-01-02
322222021-02-01NULL
422222021-02-022021-02-02

I have tried a lot of thing with GROUP BY, MAX, INNER JOIN, without success.

Thanks for any help.

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

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

发布评论

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

评论(1

2025-01-22 08:41:46

窗口函数 max() over() 似乎很适合这里。

示例或dbFiddle

with cte as (
Select *
      ,MaxDate = max([TimeStamp]) over (partition by PartNumber) 
 from YourTable
)
Update cte set [Reintegration] = MaxDate
 Where [TimeStamp] = MaxDate

更新后的表< /强>

Id  PartNumber  Timestamp     Reintegration
1   1111        2020-01-01    NULL
2   1111        2020-01-02    2020-01-02
3   2222        2021-02-01    NULL
4   2222        2021-02-02    2021-02-02

The window function max() over() seems like a nice fit here.

Example or dbFiddle

with cte as (
Select *
      ,MaxDate = max([TimeStamp]) over (partition by PartNumber) 
 from YourTable
)
Update cte set [Reintegration] = MaxDate
 Where [TimeStamp] = MaxDate

The Updated Table

Id  PartNumber  Timestamp     Reintegration
1   1111        2020-01-01    NULL
2   1111        2020-01-02    2020-01-02
3   2222        2021-02-01    NULL
4   2222        2021-02-02    2021-02-02
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文