我想要每年都有一个单调递增的标识符,每年从 1 开始。 BusinessKey 列中可能存在 NULL 行。我将在 INSERT 触发器中调用该函数:
DROP TABLE IF EXISTS [dbo].[Test];
CREATE TABLE [dbo].[Test] (
[Id] [int] IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
[Year] [int] NOT NULL,
[BusinessKey] [int]
)
GO
INSERT INTO [dbo].[Test]([Year], [BusinessKey]) VALUES
(2024, 1),
(2024, 2),
(2024, 3),
(2024, NULL),
(2024, NULL),
(2025, 1),
(2025, 2),
(2025, NULL);
-- Make a hole (gap) in the id column
DELETE FROM [dbo].[Test] WHERE [Id] = 2
GO
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY [Year] ORDER BY [Id]) AS BuisnessKeyCalculated
FROM [dbo].[Test]
这给出了:
身份证 | 年份 | 业务密钥 | 业务密钥已计算 | 预计 |
---|---|---|---|---|
1 | 2024 | 1 | 1 | 1 |
3 | 2024 | 3 | 2 | 3 |
4 | 2024 | 空 | 3 | 4 |
5 | 2024 | 空 | 4 | 5 |
6 | 2025 | 1 | 1 | 1 |
7 | 2025 | 2 | 2 | 2 |
8 | 2025 | 空 | 3 | 3 |
有人知道如何用窗口函数解决这个问题吗?
以下似乎产生了预期的结果:
select *, coalesce(
businesskey,
count(case when businesskey is null then 1 end) over (partition by year order by businesskey, id) +
max(businesskey) over (partition by year)
) as expected
from t
count() over ()
技巧将增加的行号分配给空值。 max() over ()
调整这些行号。