我是sql的新手,我需要在查询之间使用DB表中的数据。我试过但不会得到所需的结果。下面是我的表格结构
编辑:我试图按照查询中指定的时间段获得利率。如果我将期间指定为6,则利率应为3,即使指定的11利率仅为3。
假设如果期间是13,那么费率应该是4。
interest table ---------------------------------- id | year | min | max | interest | ---------------------------------- 1 | 2019 | 6 | 11 | 3 | 1 | 2019 | 12 | 0 | 4 |
下面的查询返回正确的利率。
SELECT * FROM interest WHERE 6 BETWEEN min AND max AND year=2019
但是当我传递值5时它返回null但仍然需要结果是“利率= 3”。
而当我通过13时,我应该得到“利率= 4”的结果,但我返回null。
我试过* <=和> = *即使这不起作用。我哪里错了..
我无法“修复”您的兴趣表,然后您可以通过计算最小值将其重置为0来调整它,同样地将最大值设置为0
给你的数据
select i.*,
case when min = (select min(min) from interest) then 0 else min end as minmin,
case when min = (select max(min) from interest) then 999 else max end as maxmax
from interest i
returns
+------+------+------+------+----------+--------+--------+
| id | year | min | max | interest | minmin | maxmax |
+------+------+------+------+----------+--------+--------+
| 1 | 2019 | 6 | 11 | 3 | 0 | 11 |
| 1 | 2019 | 12 | 0 | 4 | 12 | 999 |
+------+------+------+------+----------+--------+--------+
2 rows in set (0.00 sec)
然后可以使用它来检查您的输入值
select s.*
from
(
select i.*,
case when min = (select min(min) from interest) then 0 else min end as minmin,
case when min = (select max(min) from interest) then 999 else max end as maxmax
from interest i
) s
where 5 between minmin and maxmax and year = 2019;
+------+------+------+------+----------+--------+--------+
| id | year | min | max | interest | minmin | maxmax |
+------+------+------+------+----------+--------+--------+
| 1 | 2019 | 6 | 11 | 3 | 0 | 11 |
+------+------+------+------+----------+--------+--------+
1 row in set (0.00 sec)