gpt4 book ai didi

sql-server - 如何从选择查询中更新每隔一行?

转载 作者:行者123 更新时间:2023-12-02 20:58:53 24 4
gpt4 key购买 nike

我有一个 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

我想要做的是将此查询的每隔一行中的“事件”标志更新为 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

最佳答案

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

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;

关于sql-server - 如何从选择查询中更新每隔一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39228498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com