Question

Table1:

ResourceID
Name0 (STRING)
NumberOfLongons0 (INT)
LastLogon0 (DateTIME)

Table2:

ResourceID
NetbiosName0

I am trying to retrieve the following data:

NetbiosName0, Name0, NumberOfLogons0, LastLogon0 where it shows me NetbiosName0, regardless if the other data is present AND the Name0/LastLogon0 where NumberOfLogons0 is the HIGHEST for the ResourceID

UPDATE:

Tested the SQL:

SELECT T2.ResourceID, T2.Netbios_Name0, T1.Name0, T1.NumberOfLogons0, t1.LastLogon0 
FROM V_R_System T2 LEFT OUTER JOIN v_GS_NETWORK_LOGIN_PROFILE T1 
ON T2.ResourceID = T1.ResourceID 
WHERE NOT EXISTS 
(SELECT * FROM v_GS_NETWORK_LOGIN_PROFILE 
    WHERE ResourceID = T2.ResourceID AND NumberOfLogons0 > T1.NumberOfLogons0)

and got the following results:

8435 CLETESTXP-001 NT AUTHORITY\LOCAL SERVICE 
8435 CLETESTXP-001 NT AUTHORITY\NETWORK SERVICE 
8435 CLETESTXP-001 NT AUTHORITY\SYSTEM 
8435 CLETESTXP-001 TESTAGNA\JBradnan 109 3/22/2012 11:37:00 AM
Was it helpful?

Solution

In SQL Server 2008 or later, you can do this:

select
  R.ResourceID,
  R.NetbiosName0,
  L.Name0,
  L.LastLogon0
from Table2 as R
outer apply (
  select top (1) 
  -- add WITH TIES
  -- if the largest NumberOfLogons0 value can occur multiple times
    Name0,
    LastLogon0
  from Table1 as L
  where L.ResourceID = R.ResourceID
  order by NumberOfLogons0 desc
) as L

OTHER TIPS

If you need a single query to do this for multiple resources in a single command:

SELECT T2.ResourceID, T2.NetbiosName0, T1.Name0, T1.NumberOfLongons0, t1.LastLogon0
  FROM Table2 T2 LEFT OUTER JOIN Table1 T1 ON T2.ResourceID  = T1.ResourceID
  WHERE NOT EXISTS
    (SELECT * FROM Table1 WHERE ResourceID = T2.ResourceID AND NumbersOfLogons > T1.NumberOfLogons)

If you only need it for a single ResourceID at a time you can do something like the following (exact syntax depends on SQL product):

SELECT TOP 1 T2.ResourceID, T2.NetbiosName0, T1.Name0, T1.NumberOfLongons0, t1.LastLogon0
  FROM Table2 T2 LEFT OUTER JOIN Table1 T1 ON T2.ResourceID  = T1.ResourceID
  WHERE T2.ResourceID = <<ResourceID>> 
  ORDER BY T2.NumberOfLogOns0 DESC

I am not sure I understand the question correctly. But here is my guess.

DECLARE @highest int
SET @Highest = (SELECT MAX(NumberOfLogons0) FROM Table1)
SELECT T2.NetbiosName0, T1.Name0, T1.NumberOfLogons0, T1.LastLogon0
FROM Table1 T1 RIGHT JION Table2 T2
ON T1.ResourceID = T2.ResourceID
WHERE T1.NumberOfLogons0 = @Highest

Please leave me a comment if this is not what you want or there is problem in my answer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top