My question is a bit tricky to formulate, I hope it has not been asked before.
I want to select ONE row (or the single field "code" of that row) of a table by an input value that I pass to the SELECT;
Something like:
SELECT `code` FROM `example_table` WHERE .... "input"
Basically I’d want to select where "input" is greater than the value contained in the previous ‘height’ field but not greater to the next one.
The "input" to check against ‘height’ can be decimal or integer;
Here is the example table:
example_table
+----+----------+----+
| id | height | code |
+----+----------+----+
| 1 | 0 | 3.2 |
| 2 | 6 | 5.5 |
| 3 | 13 | 7.4 |
| 4 | 23 | 11.3 |
| 5 | 49 | 16.6 |
| 6 | 77 | 19.4 |
| 7 | 98 | 21.5 |
| 8 | 105 | 22.8 |
| 9 | 132 | 38.1 |
| 10 | 165 | 40.5 |
+----+--------+------+
CREATE TABLE `example_table` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`height` INT(3) NOT NULL DEFAULT '0',
`code` DECIMAL(6,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
AUTO_INCREMENT=1;
I tried passing "input" to the SELECT via WHERE but without luck. In the following examples "res" or "result" is the output of the query, and should contain the value stored in the field "code".
if input = 0 the result MUST be 3.2 [height is 0]
input = 5.47 / res 5.5 [5.47 is greater than 0 but less of ‘height'(6)]
input = 5.99 / res 5.5 [5.99 is greater than 0 but less of ‘height'(6)]
input = 6 / res 5.5 [6 is greater than 0 and equal to ‘height'(6)]
input = 6.1 / res 7.4 [6.1 is greater than 0 and 6 but less than ‘height'(13)]
input = 48.9 / res 16.6 [48.9 is greater than 0 and 6 and 13 and 23 but less than ‘height'(49)]
input = 49 / res 16.6 [49 is greater than 0 and 6 and 13 and 23 and equal to ‘height'(49)]
input = 49.1 / res 19.4 [49.1 is greater than 0 and 6 and 13 and 23 and 49 but less than ‘height'(77)]
……
……
input = 78 / res 21.5 [78 is greater than 0 and 6 and 13 and 23 and 49 and 77 but less than ‘height'(98)]
input = 165 / res 40.5 [165 is greater than 0, 6, 13, 23, 49, 77, 98, 105, 132 and equal to ‘height'(165)]
input = 165.1 / res 40.5 [165.1 is greater than 0, 6, 13, 23, 49, 77, 98, 105, 132 and 165]
How can I write a SELECT to obtain this?
I already tried many SELECT but with no success, I am not able to obtain I expect like in my examples.
2
Answers
Can you add another column to have the range in each row? That would make things easier.
Can this question be understood as finding the first
height
greater than or equal tox
?