example:
Year Number
2003 45
200233
200140
200042
199936
199828
199624
199420
199018
I would like a query to return the following:
1. A count of the number of years, commencing with the current year,
which are sequential, (in this case 5, from 2003 back to 1998).
2. Return the data for these six years, dropping all the data for the
other years.
Thank you in advance for any guidance. I've no idea where to start.
JohnFThis works assuming the current year always exists in the table:
SELECT *
FROM Sometable
WHERE yearno BETWEEN
(SELECT MAX(yearno)
FROM Sometable AS S
WHERE yearno <= YEAR(CURRENT_TIMESTAMP)
AND NOT EXISTS
(SELECT *
FROM Sometable
WHERE yearno=S.yearno-1))
AND YEAR(CURRENT_TIMESTAMP)
If there are no future years in the table, this can be simplified to:
SELECT *
FROM Sometable
WHERE yearno >=
(SELECT MAX(yearno)
FROM Sometable AS S
WHERE NOT EXISTS
(SELECT *
FROM Sometable
WHERE yearno=S.yearno-1))
If the current year doesn't exist in the table then I assume you would want
the query to return an empty result set. To do this, add the following to
the WHERE clause of either of the above:
...
AND EXISTS
(SELECT *
FROM Sometable
WHERE yearno = YEAR(CURRENT_TIMESTAMP))
--
David Portas
----
Please reply only to the newsgroup
--|||> 1. A count of the number of years, commencing with the current year,
For the count, just substitute COUNT(*) in place of * in one of the queries
I posed earlier. E.g.:
SELECT COUNT(*)
FROM Sometable
WHERE yearno >=
(SELECT MAX(yearno)
FROM Sometable AS S
WHERE NOT EXISTS
(SELECT *
FROM Sometable
WHERE yearno=S.yearno-1))
--
David Portas
----
Please reply only to the newsgroup
--
No comments:
Post a Comment