I know that there are many topics discussing nested queries, however I am getting errors on my nested query due to the functions I am using.
Sample Data:
Sample TestDate Column:
2015-05-13 13:45:14.000
2015-05-15 07:33:13.000
2015-05-18 06:07:11.000
2015-05-19 02:58:13.000
2015-05-22 14:08:42.000
2015-05-26 11:01:29.000
2015-05-26 11:01:50.000
2015-05-27 07:19:32.000
2015-05-15 08:04:28.000
2015-05-15 10:32:23.000
2015-05-22 14:11:26.000
2015-05-27 07:16:57.000
2015-05-29 08:50:36.000
2015-05-15 10:38:23.000
2015-05-19 03:08:53.000
2015-05-27 13:41:47.000
2015-05-29 08:47:56.000
2015-05-15 07:50:04.000
2015-05-18 06:20:28.000
2015-05-19 06:32:24.000
2015-05-26 11:00:58.000
2015-05-22 14:12:15.000
2015-05-26 10:57:17.000
I am looking to query the last 7 DATES with data (may not be the last 7 days).
My query to return the last 7 Dates with data works well.
-- Set the return record count to the last 7 days
SET ROWCOUNT 7
--Get the Distinct Dates
SELECT DISTINCT(CONVERT(VARCHAR, CONVERT(DATETIME,[TestDate]),23)) AS DT
FROM [SERVER].[dbo].[TABLE]
--Get the last 60 days
WHERE [TestDate] BETWEEN (Getdate() - 60) AND Getdate()
--Start at the current date and go backwards.
ORDER BY DT DESC
-- reset the return record count to prevent issues with further queries.
SET ROWCOUNT 0
This provides the following result:
DT
2015-05-29
2015-05-27
2015-05-26
2015-05-22
2015-05-19
2015-05-18
2015-05-15
Now, I want to use those 7 entries to pull the data for those dates.
Usually I would do a
SELECT * WHERE [TestDate] >= '2015-05-29' AND [TestDate] <= '2015-05-30'
for example (cumbersome I know).
A) I get errors with the SET function in a nested query.
B) How to make the proper WHERE statement. One option is to use the first and last result (2015-05-29 and 2015-05-15) from the query
(WHERE [TestDate] >= 'FIRST_RESULT' AND [TestDate] <= 'LAST_RESULT')
EDIT:
So from the table I added above, I would want data from 2015-05-15 - 2015-05-29 (ie the results from the query), but not from the data on date 2015-05-13, since data from the 13 th is the 8 th day.