我有一张这样的桌子,我很难更新它
code descd slnum
---------------------
10 a 0
10 b 0
12 c 0
12 d 0
11 e 0
12 f 0
我必须像这样更新此表而不使用ROW_NUMBER()
只使用if else循环我该怎么做?
code descd slnum
----------------------
10 a 1
10 b 2
12 c 1
12 d 2
11 e 1
12 f 3
答案 0 :(得分:1)
对于SQL 2012 +
;WITH rownum(code, descd, slnum) AS (
SELECT 10, 'a', 0
UNION SELECT 10, 'b', 0
UNION SELECT 12, 'c', 0
UNION SELECT 12, 'd', 0
UNION SELECT 11, 'e', 0
UNION SELECT 12, 'f', 0
) SELECT code, descd, COUNT(*) OVER (PARTITION BY code ORDER BY code
ROWS UNBOUNDED PRECEDING) FROM rownum o ORDER BY descd
答案 1 :(得分:0)
试试这个
DECLARE @Tbl TABLE(code VARCHAR(5), descd VARCHAR(5), slnum int)
INSERT INTO @Tbl
( code, descd)
VALUES
('10', 'a'),
('10', 'b'),
('12', 'c'),
('12', 'd'),
('11', 'e'),
('12', 'f')
DECLARE @TempTable TABLE(code VARCHAR(5), descd VARCHAR(5), RowId int)
DECLARE @RowId INT = 1
WHILE @RowId <= (SELECT COUNT(*) FROM @Tbl)
BEGIN
INSERT INTO @TempTable
SELECT TOP 1
T.code ,
T.descd ,
@RowId
FROM
@Tbl T LEFT JOIN
@TempTable L ON L.code = T.code AND L.descd = T.descd
WHERE
L.code IS null
ORDER BY
T.code,
T.descd
UPDATE @Tbl
SET slnum = (SELECT COUNT(1) FROM @TempTable A WHERE [@Tbl].Code = A.Code)
WHERE
[@Tbl].Code = (SELECT TOP 1 Y.code FROM @TempTable Y WHERE RowId = @RowId) AND
[@Tbl].descd = (SELECT TOP 1 Y.descd FROM @TempTable Y WHERE RowId = @RowId)
SET @RowId += 1
END
SELECT * from @Tbl
结果:
code descd slnum
10 a 1
10 b 2
12 c 1
12 d 2
11 e 1
12 f 3
答案 2 :(得分:0)
; with rownum(code,descd,slnum)AS(
SELECT 10,'a',0
UNION SELECT 10,'b',0
UNION SELECT 12,'c',0
UNION SELECT 12,'d',0
UNION SELECT 11,'e',0
UNION SELECT 12,'f',0
)SELECT代码,descd,COUNT(*)OVER(PARTITION BY代码ORDER BY代码
)FROM rownum ORDER BY descd