【问题标题】:Write SQL query and get values for given range using <= (or) between and (or) any other使用 <= (or) between and (or) any other 编写 SQL 查询并获取给定范围的值
【发布时间】:2022-01-12 06:10:30
【问题描述】:
create table demo4 
(
    sno int, 
    fromvalue int, 
    tovalue int
)

insert into demo4 
values (1, 2002, 2002), (2, 2003, 2003), (3, 2004, 2004), (4, 2001, 2010),
       (5, 2006, 2007), (6, 2011, 2011), (7, 2005, 2005), (8, 2006, 2010),
       (9, 2006, 2011), (10, 2008, 2009)


            |sno   |fromvalue |tovalue|
            +------+----------+-------+
            |  1   | 2002     |  2002 |
            |  2   | 2003     |  2003 |
            |  3   | 2004     |  2004 |
            |  4   | 2001     |  2010 |
            |  5   | 2006     |  2007 |
            |  6   | 2011     |  2011 |
            |  7   | 2005     |  2005 |
            |  8   | 2006     |  2010 |
            |  9   | 2006     |  2011 |
            | 10   | 2008     |  2009 |

从上表中,我想得到 sno 值作为 1,2,3,4 对于给定的范围 2002-2004 来自 value 和 tovalue

我尝试了以下查询,但它不起作用

select * 
from demo2 
where (fromvalue between 2002 and 2004) 
   or (tovalue between 2002 and 2004)   

-- 1, 2, 3 are fetched (4 is not fetched)

select * 
from demo2 
where 2002 <= fromvalue 
  and tovalue <= 2004 

-- 1, 2, 3 are fetched (4 is not fetched)

【问题讨论】:

  • 你自己尝试过什么?
  • 我试过:select * from demo2 where (fromvalue between 2020 and 2004) or (tovalue between 2002 and 2004) select * from dem02 where 2022
  • 显示您每次尝试的实际结果,并准确解释为什么您的结果不符合您的要求。另外,为什么 4 是您的预期结果之一? 2002和2004之间是2001还是2010??
  • (4, 2001, 2010) 不是预期结果,因为 2001 和 2010 都不是介于 2002 年和 2004 年之间!你问反了??
  • @JonArmstrong 因为 2002 和 2004 存在于 2001(fromvalue) 和 2010(tovalue) 所以它需要在结果集中

标签: sql range between


【解决方案1】:

如果要区间交集(重叠)

select * 
from demo4 
where fromvalue <= 2004 and tovalue >= 2002 

对于 2001-2010 年的间隔,它将是

select * 
from demo4 
where fromvalue <= 2010 and tovalue >= 2001;

一般情况下,s1 - e1s2 - e2 的间隔重叠条件是 s1&lt;=e2 and s2&lt;=e1 所以对于 fromvalue - tovalue2001 - 2010 它正好是 fromvalue &lt;= 2010 and 2001 &lt;= tovalue

【讨论】:

  • 如果我考虑你的查询,那么对于 2001-2010 范围,我只得到 (sno:4) 但我需要得到 1,2,3,4,5,7,8,9,10 (即除 6 之外的所有值)
  • @ChaitanyaReddy,不,你会得到你所需要的。
猜你喜欢
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 2013-01-27
  • 2023-04-08
  • 2015-07-09
  • 1970-01-01
  • 2021-11-14
相关资源
最近更新 更多