I’m wondering if there is a more concise way of finding trees that have had a Vigor rating of 6, 8 or 9 for the past 5 years.
In the past, I was looking trees dead only for the past two years, and I used a query like this:
set @sampleyear = 2020;
select *
from tblTree
where tblTree.Year=@sampleyear
and (((Year = @sampleyear) and (Vigor not in (6,8,9))) or ((Year = (@sampleyear-1)) and (Vigor not in (6,8,9))));
I could expand the last line to just continue back for 5 years, but I was wondering if anyone could think of a better way?
Thank you!
Sample data could look like this, the query would return rows with year 2020 and tree id 1 but not 2:
tree id | year | vigor |
---|---|---|
1 | 2015 | 1 |
1 | 2016 | 1 |
1 | 2017 | 1 |
1 | 2018 | 6 |
1 | 2019 | 6 |
1 | 2020 | 6 |
2 | 2015 | 6 |
2 | 2016 | 6 |
2 | 2017 | 6 |
2 | 2018 | 6 |
2 | 2019 | 6 |
2 | 2020 | 6 |
2
Answers
You can do this by comparing
YEAR
andNOW
subtracting an arbitraryinterval
set by you. IEA side note, you should not name your field
year
in your table. This is a reserved function in MySQL. You can "get around" it by putting it in ticksWhich using ticks is always best practice, but it’s even better practice to use the ticks AND not use reserved functions as names for your fields.
Your existing query does not make much sense. Here it is with
@sampleyear
expanded:Which is the same as just:
This is the basic extension of your existing query, just using
>=
comparison for the year instead of listing them explicitly and grouping so as to return just the list of tree_ids:These are variations on this theme, which you may find useful:
Any of these queries can be easily joined back to the full table if you want to see the full records for the time span being looked at: