我有以下表结构:
Id | TransNbr | Type |
-------+----------+------+
1235 | 220 | A |
1236 | 221 | A |
1237 | 220 | A |
1238 | 220 | B |
1239 | 221 | B |
我需要在此表中添加一个新列,以指示这是否是 A
类型的第一个 TransNbr
。
我能够让以下 SELECT
查询正常工作...但我不确定现在如何将新的 populate FirstTime
列添加到 发票
表:
SELECT
*,
CASE
WHEN (ROW_NUMBER() OVER(PARTITION BY TransNbr ORDER BY Id)) = 1
THEN 1
ELSE 0
END FirstTime
FROM INVOICE
WHERE Type = 'A'
最佳答案
如果您想更新 id 为 1235 的行上的字段,那么您可以这样做:
with toupdate as (
select i.*, row_number() over (partition by type order by id) as seqnum
from invoice
where type = 'A'
)
update toupdate
set FirstTime = 1;
如果这没有达到您真正想要的效果,您可以调整 CTE 中的逻辑。
如果您没有 FirstTime
标志,您可以执行以下操作:
alter table invoice add FirstTime tinyint default 0;
关于SQL Server : identify first row value appears in column and insert into table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45555997/