检查后续记录是否有特殊约束

时间:2014-12-11 15:14:54

标签: sql hsqldb consistency

数学规则必须适用于具有相同名称标识符的所有记录:

x(n)= x(n-1)+ y(n-1)其中n是按x排序的元素。

特殊情况:如果y = 0,则x的以下值不需要遵守此规则。举个例子:

Name    X    Y
   a    0    1
   a    1    2
   a    2    5   <----- this is invalid because 1 + 2 != 2
   b    0    1
   b    1    0
   b    14   3   <----- this is okay because the preceding element had y = 0
   b    16   1   <----- this is invalid because 14 + 3 != 16

任务是过滤无效元素。

如果没有y = 0的特殊情况,我想出了这个:

SELECT * FROM TABLE EXCEPT
SELECT NAME, X, Y FROM (
SELECT * FROM TABLE JOIN SELECT NAME AS N, X AS XX, Y AS YY
ON NAME = N WHERE X = 0 OR XX+YY = X)

有没有人有任何建议如何处理Y = 0?

1 个答案:

答案 0 :(得分:2)

我找到了解决问题的方法。我假设您的表名为&#39; a&#39;

以下是代码:

SELECT name,
       x,
       y
FROM
  (SELECT a1.name,
           a1.x,
           a1.y,

     (SELECT a3.x + a3.y
      FROM a AS a3
      WHERE a3.name=a1.name
        AND a3.y<>0
        AND a3.x =
          (SELECT max(a2.x)
           FROM a AS a2
           WHERE a2.name=a1.name
             AND a2.x<a1.x)) AS s1
   FROM a AS a1)
WHERE s1 IS NULL
  OR x=s1

结果是:

a   0   1
a   1   2
b   0   1
b   1   0
b   14  3