使用SQL Server 2000,考虑具有超过400,000条记录的源表。
任务是选择每个regno
条目,其中包含具有重复项或多个条目的动态递增rowid
或序列号。对于那些在源表中没有重复条目的人,rowid
应该只是null
。
以下是所需输出的示例:
regno rowid 100 1 100 2 100 3 200 null 300 4 300 5 400 null 500 null 600 6 600 7
问题: 在SQL Server 2000中使用TSQL进行所需序列递增的查询是什么?
答案 0 :(得分:2)
如果我的评论是正确的(600应该是6,7),那么看看这个
DECLARE @Table TABLE(
regno INT,
rowid INT
)
INSERT INTO @Table (regno,rowid) SELECT 100, NULL
INSERT INTO @Table (regno,rowid) SELECT 100, NULL
INSERT INTO @Table (regno,rowid) SELECT 100, NULL
INSERT INTO @Table (regno,rowid) SELECT 200, NULL
INSERT INTO @Table (regno,rowid) SELECT 300, NULL
INSERT INTO @Table (regno,rowid) SELECT 300, NULL
INSERT INTO @Table (regno,rowid) SELECT 400, NULL
INSERT INTO @Table (regno,rowid) SELECT 500, NULL
INSERT INTO @Table (regno,rowid) SELECT 600, NULL
INSERT INTO @Table (regno,rowid) SELECT 600, NULL
DECLARE @TempTable TABLE(
ID INT IDENTITY(1,1),
regno INT
)
INSERT INTO @TempTable (regno)
SELECT regno
FROM @Table
SELECT regno,
CASE
WHEN (SELECT COUNT(1) FROM @TempTable WHERE regno = t.regno) = 1
THEN NULL
ELSE (SELECT COUNT(1) FROM @TempTable WHERE regno = t.regno) - (SELECT COUNT(1) FROM @TempTable WHERE regno = t.regno AND ID > t.ID) +
(SELECT COUNT(1) FROM @TempTable WHERE regno < t.regno AND regno IN (SELECT regno FROM @TempTable GROUP BY regno having COUNT(1) > 1))
END Val
FROM @TempTable t
答案 1 :(得分:0)
提取非唯一记录的查询将是
select regno,count(*) from table group by regno having count(*) > 1
我不太了解MSSQL如何生成递增序列号来更新与查询匹配的记录。
答案 2 :(得分:0)
没有临时表:
DECLARE @Table TABLE(
regno INT
)
INSERT INTO @Table (regno) SELECT 100
INSERT INTO @Table (regno) SELECT 100
INSERT INTO @Table (regno) SELECT 100
INSERT INTO @Table (regno) SELECT 200
INSERT INTO @Table (regno) SELECT 300
INSERT INTO @Table (regno) SELECT 300
INSERT INTO @Table (regno) SELECT 400
INSERT INTO @Table (regno) SELECT 500
INSERT INTO @Table (regno) SELECT 600
INSERT INTO @Table (regno) SELECT 600
select regno, null as rowid from @Table group by regno having count(*) = 1
union
select regno, row_number() OVER (ORDER BY a.regno) as rowid
from @table a
where regno in (select regno from @table group by regno having count(*) > 1)
regno rowid
----------- --------------------
100 1
100 2
100 3
200 NULL
300 4
300 5
400 NULL
500 NULL
600 6
600 7
糟糕 - 在发布此内容之前,没有看到您想在SQL 2000中执行此操作...请忽略我的查询。在SQL 2000中,您需要一个临时表来生成序列。