比较值范围与另一个值范围mysql

时间:2016-12-22 10:43:18

标签: mysql sql

我在MySQL数据库中有一个表(shrewd_db.threshold),我执行了以下代码

select  id_indicator, id_threshold, activation_begin_value, activation_end_value 
from shrewd_db.threshold
where active =1
group by id_indicator, id_threshold;

我的输出如下:

 id_indicator   id_threshold    activation_begin_value  activation_end_value 

   2                5                   4                 58
   2                6                   3                  3
   2                7                   1                  2
   2                8                   0                  0
   4               13                   0                4.5
   4               15                 4.1                5.5
   4               16                5.51                  6
   4               17                6.01                100

每个id_indicator都有四个id_threshold范围。

现在进行数据验证检查我需要找出每个指标id_threshold(activation_begin_value和activation_end_value)不会落入另一个阈值。

我想要的输出应该是:

 id_indicator   id_threshold    activation_begin_value  activation_end_value 


   4               13                   0                4.5
   4               15                 4.1                5.5

其中id_indicator(4)两个id_threshold(13,15)值相互下降。主要识别阈值不得重叠

2 个答案:

答案 0 :(得分:1)

我认为你的意思是激活期不能重叠,对吗?

然后检查这个的查询看起来如下:

select distinct t1.* from threshold t1, threshold t2 where
  t1.id_indicator = t2.id_indicator and
  t1.id_threshold <> t2.id_threshold and
    (  t1.activation_begin_value BETWEEN t2.activation_begin_value and 
       t2.activation_end_value
    OR t1.activation_end_value BETWEEN t2.activation_begin_value and 
       t2.activation_end_value
    )

使用以下架构测试查询:

CREATE TABLE threshold
    (`id_indicator` int, `id_threshold` int, `activation_begin_value` numeric(5,2), `activation_end_value` numeric(5,2))
;

INSERT INTO threshold
    (`id_indicator`, `id_threshold`, `activation_begin_value`, `activation_end_value`)
VALUES
    (2, 5, 4, 58),
    (2, 6, 3, 3),
    (2, 7, 1, 2),
    (2, 8, 0, 0),
    (4, 13, 0, 4.5),
    (4, 15, 4.1, 5.5),
    (4, 16, 5.51, 6),
    (4, 17, 6.01, 100)
;

并产生以下结果:

id_indicator|id_threshold|activation_begin_value | activation_end_value
------------|------------|-----------------------|---------------------
           4|          15|                    4.1|                  5.5
           4|          13|                      0|                  4.5

答案 1 :(得分:0)

您的查询 - 您要获得输出 - 必须抛出错误

它可以 -     选择id_indicator,id_threshold,min(activation_begin_value),     最大值(activation_end_value)     来自shrewd_db.threshold     其中active = 1     group by id_indicator,id_threshold;

如果你纠正了这个并在一些临时表中取出这个输出,然后写自我联接激活_begin_value,activation_end_value我想你可能会得到你的结果。

否则将光标写在上面的输出上并逐行比较......如果它是一次性作业且性能没有问题..