使用 SQL Server 2005
我有一个包含以下列的表格
ID 姓名 日期 值
我想从表中选择按日期不存在四个连续零的所有行。我该怎么做呢?下面是我的意思的一个例子。
id name date value
1 a 1/1/2010 5
2 a 1/2/2010 3
3 a 1/3/2010 5
4 a 1/4/2010 0
5 a 1/7/2010 0
6 a 1/8/2010 0
7 a 1/9/2010 2
8 a 1/10/2010 3
9 a 1/11/2010 0
10 a 1/15/2010 0
11 a 1/16/2010 0
12 a 1/17/2010 0
13 a 1/20/2010 4
14 a 1/21/2010 4
我希望查询结果包含除 id 9-12 之外的所有行。
最佳答案
假设您按 ID 对行进行排序,但您只需将 ORDER BY id
更改为其他内容,它应该仍然有效。
使用 this Kodyaz Development Resources site 上找到的 T-SQL CTE我能够创建以下代码。我让它工作,所以它删除了有两个连续零的行,而不是 4 个,因为我在我的代码上测试了它,只是更改了表/行名称。
WITH CTE as (
SELECT
RN = ROW_NUMBER() OVER (ORDER BY id),
*
FROM tablename
)
SELECT
[Current Row].*
FROM CTE [Current Row]
LEFT JOIN CTE [Previous Row] ON
[Previous Row].RN = [Current Row].RN - 1
LEFT JOIN CTE [Next Row] ON
[Next Row].RN = [Current Row].RN + 1
WHERE
not([Current Row].value = 0 AND [Next Row].value = 0) AND
// this deletes the row where value is zero and the next rows value is zero
not([Previous Row].value = 0 AND [Current Row].value = 0)
// this deletes the row where value is zero and the previous rows value is zero
要使其适合您的情况,您所需要做的就是将每个可能的组合放入 WHERE
语句中。例如,处理此行和接下来的 3 行等于 0 或此行是上一行和接下来的 2 行。
关于sql - 过滤 SQL Server 2005 中的不良数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3112222/