Reputation: 3
I've got a 2 part problem where through the use of google managed to find the answer to the first part at SQL get the last date time record
User Osy code work really well for me,
Osy's code below!
select filename, dates, status
from yt a
where a.dates = (select max(dates)
from yt b
where a.filename = b.filename)
The query returns only the latest dates for each filename.
If I could just stick to the same example question as url above.
This is the table used in the example:
yt
table:
+---------+------------------------+-------+
|filename |Dates |Status |
+---------+------------------------+-------+
|abc.txt |2012-02-14 12:04:45.397 |Open |
|abc.txt |2012-02-14 12:14:20.997 |Closed |
|abc.txt |2013-02-14 12:20:59.407 |Open |
|dfg.txt |2012-02-14 12:14:20.997 |Closed |
|dfg.txt |2013-02-14 12:20:59.407 |Open |
+---------+------------------------+-------+
The second part of the problem:
What I am now trying to achieve is that I have a second table and would like to join the results from the query above on the filename and return the user.
Table2
+--------+--------+
|filename |ref |
+---------+--------+
|abc.txt |Heating |
|dfg.txt |Cooling |
+---------+---- ---+
Result that I am trying to achieve from the query is as follows, using Osy's code above to return only the latest for each entry per device, and then to display the ref column and not display the filename
Example:
+---------+------------------------+-------+
|ref |Dates |Status |
+---------+------------------------+-------+
|Heating |2013-02-14 12:20:59.407 |Open |
|Cooling |2013-02-14 12:20:59.407 |Open |
+---------+------------------------+-------+
I can use a inner join directly on the yt table but cannot get is to combine (nest) with the code from Osy above.
Using SQL Server 2012. Please let me know if I left out anything.
Thank you.
Upvotes: 0
Views: 157
Reputation: 13949
This might be faster way to do it.
SELECT [ref],
[dates],
[status]
FROM (SELECT a.[filename],
a.[dates],
a.[status],
t2.[ref],
ROW_NUMBER() OVER (PARTITION BY a.[filename] ORDER BY a.[dates] DESC) [Rn]
FROM yt a
JOIN Table2 t2 ON a.[filename] = t2.[filename]
) t
WHERE t.Rn = 1
Upvotes: 1
Reputation: 138
Speculating the bottom query but is should work:
SELECT a.ref, MAX(b.Dates), b.Status
FROM Table2 AS a INNER JOIN yt AS b ON a.ref=b.filename AND b.Status='Open'
GROUP BY a.ref, b.Status
Let me know if it works
Upvotes: 0
Reputation: 77866
Continuing with your posted example code, again perform one more JOIN
with Table2
like
select t2.ref, xx.Dates, xx.Status
from Table2 t2 join (
select filename, dates, status
from yt a where a.dates = (
select max(dates)
from yt b
where a.filename = b.filename
)) xx on t2.filename = xx.filename;
Upvotes: 0