I have a list of inventory entries. Each entry has a date, item name, and volumes. What I'm doing now is selecting the top 10 items based on the most recent-date volumes, and then tracking the volumes of these items over the past 5 days in my table. The one piece I'm missing is that I would like to order the resulting table based on the most recent-date volume order of the items, i.e.
Date Item Volumes
1/20 Dog 5
1/20 Bird 4
1/20 Cat 2
1/19 Dog 3
1/19 Bird 6
1/19 Cat 10
1/18 Dog 0
1/18 Bird 2
1/18 Cat 0
Below is a scrubbed version of the sql code I'm running. As of now the second sort I'm doing after sorting on the date is just sorting alphabetically on the item name.
SELECT
TOP_VOLUMES.NAME,
DATA.VOLUMES,
DATA.TIMESTAMP
FROM DATA
RIGHT JOIN
(SELECT TOP 10 NAME
FROM DATA
WHERE TIMESTAMP = (SELECT MAX(TIMESTAMP) FROM DATA)
ORDER BY VOLUMES DESC, NAME) AS TOP_VOLUMES
ON TOP_VOLUMES.NAME = DATA.NAME
WHERE ((SELECT MAX(TIMESTAMP) FROM DATA) - DATA.TIMESTAMP < 5)
ORDER BY DATA.TIMESTAMP DESC , DATA.NAME;
I would really like to avoid creating any temp tables for this. Is there any way to do it within the select statement within the join? Any help would be greatly appreciated!