如何从选择查询更新每隔一行?

时间:2016-08-30 13:13:10

标签: sql-server

我有一个SQL查询,从我的数据库中的表中提取160条记录。

SELECT TableID, Number, Active FROM Table WHERE Number IN (SELECT Number 
FROM Table
GROUP BY Number, Active
HAVING COUNT(*) > 1 AND COUNT(*) < 3
AND Active = 1)
ORDER BY Number, TableID

我要做的是在此查询的每隔一行中将Active标志更新为0。有点像:

UPDATE Table SET Active = 0 where Number in (
SELECT TableID, Number, Active FROM Table WHERE Number IN (SELECT Number 
FROM Table
GROUP BY Number, Active
HAVING COUNT(*) > 1 AND COUNT(*) < 3
AND Active = 1 AND Number %2 = 1) -- this is where I need assistance
ORDER BY Number, TableID)

如何成功执行此查询?类似的问题没有提供我正在寻找的答案。

编辑:以下是来自热门查询的示例缩短数据集:

TableID Number  Active
38      662         1
177     662         1
58      702         1
171     702         1
13      716         1
165     716         1
77      814         1
164     814         1
63      1103        1
174     1103        1

预期结果:

TableID Number  Active
    38      662         1
    177     662         0
    58      702         1
    171     702         0
    13      716         1
    165     716         0
    77      814         1
    164     814         0
    63      1103        1
    174     1103        0

1 个答案:

答案 0 :(得分:3)

如果我理解正确的话,应该这样做:

WITH CTE AS
(
    SELECT  *, 
            COUNT(*) OVER(PARTITION BY Number, Active) N,
            ROW_NUMBER() OVER(PARTITION BY Number, Active ORDER BY Number) RN
    FROM dbo.YourTable
    WHERE Active = 1
)
UPDATE CTE
SET Active = 0
WHERE N = 2 AND RN % 2 = 1;

您需要确保查询首先返回正确的行:

WITH CTE AS
(
    SELECT  *, 
            COUNT(*) OVER(PARTITION BY Number, Active) N,
            ROW_NUMBER() OVER(PARTITION BY Number, Active ORDER BY Number) RN
    FROM dbo.YourTable
    WHERE Active = 1
)
SELECT *
FROM CTE
WHERE N = 2;