I working on test tool, reporting for it.
SO, there is a test hich can be performed automatically several times per day. And In one report I need to show historical data per test (chart with Date and Number of test passed) and the number of passed tests for latest day.
Lef’t create model of this issue:
I have such data structure (simplified):
DECLARE @TestResults TABLE
(
TestId INT,
DateOfResult DATE,
TestPassedCount INT
);
INSERT INTO @TestResults VALUES (1,DATEADD(day,-3,GETDATE()), 6);--This test passed 4 times 3 days ago
INSERT INTO @TestResults VALUES (1,DATEADD(day,-1,GETDATE()), 4); --This test passed 4 times yesterday
INSERT INTO @TestResults VALUES (1,GETDATE(), 5); --This test passed five times today
INSERT INTO @TestResults VALUES (2,DATEADD(day,-3,GETDATE()), 6);--This test passed 4 times 3 days ago
INSERT INTO @TestResults VALUES (2,DATEADD(day,-1,GETDATE()), 4); --This test passed 4 times yesterday
SELECT * FROM @TestResults;
Last select will return me a data set:
TestId DateOfResult TestPassedCount
1 2012-06-12 6
1 2012-06-14 4
1 2012-06-15 5
2 2012-06-12 6
2 2012-06-14 4
How can I also get with this query (in separate column) the number of passed tests for max available date? For example, for test with ID 1 I have data for 12,13,14 of June. So, in separate column I need to get 5 because on latest date (max(DateOfResults)) there is five passed tests?
I’m using SQL Server 2012.
Thank you!
Update: I foound the way:
SELECT SubQ.*, r.TestPassedCount FROM (
SELECT *, Max(t.DateOfResult) OVER (PARTITION BY t.TestId ORDER BY t.TestId) as MaxDate FROM @TestResults t
) AS SubQ JOIN @TestResults r ON r.TestId = SubQ.TestId AND r.DateOfResult = SubQ.MaxDate
Now I need to apply it to the real queries 🙂
Are there any other ways to do?
I can’t execute your solution, maybe are missing something? I’m having this error (and I can’t figure why):
So, my version of the query is almost equal: