Forum Discussion
scabral79
Nov 29, 2023Copper Contributor
Snapshot query for end of year
I have the following table with sample data: drop table if exists #temp select '1' as LocationId, '2512' as EquipmentNum, '7459' as RecNum, cast('5/2/2023 13:30' as datetime) as VersionBeginDt ...
BabatundeDallas
Jan 19, 2024Brass Contributor
scabral79 you can achieve this by using a combination of common table expressions (CTEs) and the ROW_NUMBER() window function to identify the latest row for each year.
WITH YearlyData AS (
SELECT
LocationId,
EquipmentNum,
RecNum,
VersionBeginDt,
ROW_NUMBER() OVER (PARTITION BY LocationId, EquipmentNum, RecNum, YEAR(VersionBeginDt) ORDER BY VersionBeginDt DESC) AS RowNum
FROM
#temp
WHERE
YEAR(VersionBeginDt) BETWEEN 2018 AND 2023
)
SELECT
LocationId,
EquipmentNum,
RecNum,
VersionBeginDt
FROM
YearlyData
WHERE
RowNum = 1
ORDER BY
LocationId,
EquipmentNum,
RecNum,
VersionBeginDt;
Let me know if this works for you. @ me in replies, or I'll lose your thread!!!
Note:
If this post helps, please consider Accepting it as the solution to help others find it more quickly. OR
If my answers help arrive at a solution? Give it a kudos by clicking the Thumbs Up!
If my answers help arrive at a solution? Give it a kudos by clicking the Thumbs Up!
Best Regards,
Dallas.