I've got a table called theTable
from where I want to import some data. theTable
includes Product stock values, and I am only interested in finding the stock balances at the last day of each month in a range of 6 months.
I have a column called DateKey
which looks like yyyymmdd
and describes the date for which a stock balance is recorded.
As an example, I'd like to be able to deduce the stockValue
at the DateKey
values: 20160131,20160331
For this I've tried:
CREATE TABLE #theTable
(
DateKey INT,
stockValue INT
);
INSERT INTO #theTable
VALUES (20160131, 4), (20160130, 5),
(20160312, 5), (20160331, 4);
SELECT DateKey, stockValue
FROM #theTable
WHERE DateKey BETWEEN CONVERT(VARCHAR(8), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 16, 0), 112)
AND CONVERT(VARCHAR(8), DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE()) - 13, -1), 112)
(where I've added the convert() shenanigans in order to avoid error of DateKey not being of type DateTime
)
But this (naturally) returns:
DateKey stockValue
20160131 4
20160130 5
20160312 5
20160331 4
how can I adjust this SQL statement to only include:
DateKey stockValue
20160131 4
20160331 4
i.e the last days of the months over my specified date range?
EDIT:
The question is if there is a way to get only the last day's values without having to hard code a `WHERE DATEKEY IN ('20160131','20160228','20160331') as there will be many different values I'd like to choose from, which would render a hard coded solution to become very prone to error and time consuming.