Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi,this will be my first post to sqlteam.com.I've been trying to work out this problem for awhile, and figured I really need help. I have a set of data that shows the results of a number of tests that I have been doing on a software. Each test I have done records the test_ID, test_Result, and the date_Tested. An example of the columns would be like this:test_ID | test_Result | date_Tested3112 | PASS | 2007-11-23 09:29:40.2303112 | FAIL | 2007-02-22 09:22:00.2303112 | FAIL | 2007-01-21 09:21:40.2343113 | PASS | 2007-11-23 09:29:40.2303114 | PASS | 2007-11-23 09:29:40.2303115 | FAIL | 2008-01-23 09:29:40.2303115 | PASS | 2007-11-23 09:29:40.2303116 | FAIL | 2007-12-25 09:29:40.2303116 | PASS | 2007-11-23 09:29:40.230Now what I want is ONLY the latest result for each test_ID, I do not want repeated test_IDs to show up. So my expected result should be:test_ID | test_Result | date_Tested3112 | PASS | 2007-11-23 09:29:40.2303113 | PASS | 2007-11-23 09:29:40.2303114 | PASS | 2007-11-23 09:29:40.2303115 | FAIL | 2008-01-23 09:29:40.2303116 | FAIL | 2007-12-25 09:29:40.230Is there a way I can query this? I've tried using "distinct test_ID" but it would still show the repeated test_ID due to the date_Tested not being the same.. also Group By will not work. I'm not sure what to do here. Any ideas anyone?Thanks in advance.
jdaman
Constraint Violating Yak Guru
354 Posts
Posted - 2008-02-06 : 16:12:17
If you are using Sql 2005:
SELECT test_Id, test_Result, date_TestedFROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY test_ID ORDER BY date_Tested ) AS rn, test_Id, test_Result, date_Tested FROM YourTable ) aWHERE rn = 1
genelam
Starting Member
2 Posts
Posted - 2008-02-06 : 16:36:14
Thanks! Thats exactly what I was looking for. Just a question, why is it necessary to have "a" after the inner select clause?
jdaman
Constraint Violating Yak Guru
354 Posts
Posted - 2008-02-06 : 16:46:57
Sql Server requires that derived tables have a corresponding table alias. In this case the "a" is there merely to fulfill that requirement.