基于一对功能,在SQL Server表上添加标志

发布于 2025-02-07 13:49:24 字数 313 浏览 0 评论 0原文

我在SQL Server中有一个带ID,代码和产品的表。我想添加一个标志,最终像以下方式:

Id Code Prod Flag
0  101  A    0
1  101  B    0
2  101  A    1
3  101  A    1
4  101  B    1
5  160  B    0
6  160  A    0
7  160  B    1
8  190  A    0
9  190  B    0

对于每个配对代码 - (例如101-A,有3个案例),标志应为第一个ID假设0,否则为1个。

我该怎么做?

I have a table in SQL Server with Id, Code and Prod. I want to add a flag and end up like:

Id Code Prod Flag
0  101  A    0
1  101  B    0
2  101  A    1
3  101  A    1
4  101  B    1
5  160  B    0
6  160  A    0
7  160  B    1
8  190  A    0
9  190  B    0

For each pair Code-Prod (eg. 101-A, which has 3 cases), the flag should assume 0 for the first Id, 1 otherwise.

How do I do that?

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

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

发布评论

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

评论(1

缱绻入梦 2025-02-14 13:49:24

理想情况下,使用 row_number()窗口函数解决了这一点,并结合了可更新的CTE:

with upd as (
  select *, Row_Number() over(partition by Concat(code,prod) order by id) rn
  from t
)
update upd 
set flag = case when rn = 1 then 0 else 1 end;

This is ideally solved with row_number() window function, combined with an updatable CTE:

with upd as (
  select *, Row_Number() over(partition by Concat(code,prod) order by id) rn
  from t
)
update upd 
set flag = case when rn = 1 then 0 else 1 end;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文