2

I have a temp table (#TempTable) which looks like this:

AID         StartTime   EndTime     StartSID EndSID     Name

79F05D45    2013-07-02  2013-07-03  1226349  1227338    
79F05D45    2013-07-03  2013-07-03  1227381  1227901    
79F05D45    2013-07-03  2013-07-03  1233976  1233977    John Pringle
79F05D45    2013-07-03  2013-07-03  1234386  1234452    
79F05D45    2013-07-03  2013-07-03  1235138  1235147    
79F05D45    2013-07-03  2013-07-03  1235669  1235708    Mike Gordon
79F05D45    2013-07-03  2013-07-03  1235828  1239004    Jeff Smith

How do I use the Aggregate function on Name so that when I GROUP BY StartTime and EndTime I get John Pringle in the Name column (I tried using MIN(Name) but it gives me blank value and If I use MAX(Name) I get Jeff Smith )

Basically, my requirement is to get the first available value in column Name

Here is my Query:

SELECT
    TT.AID,
    MIN(StartTime) as StartTime,
    MAX(EndTime) as Endtime,
    MIN(StartSSID) as StartSID,
    MAX(EndSSID) AS EndSID,
    -- I tried MIN(Name) here but I get empty cell, MAX(Name) gives wrong result. Basically I want first available value in the Name column here (which is John Pringle).
    FROM
        #TempTable TT
    GROUP BY TT.AID, StartTime, EndTime

Result I get:

AID         StartTime   EndTime     StartSID EndSID     Name

79F05D45    2013-07-02  2013-07-03  1226349  1227338    
79F05D45    2013-07-03  2013-07-03  1227381  1239004

Result I am aiming for:

AID         StartTime   EndTime     StartSID EndSID     Name

79F05D45    2013-07-02  2013-07-03  1226349  1227338        
79F05D45    2013-07-03  2013-07-03  1227381  1239004    John Pringle

Thanks!

Learner
  • 3,904
  • 6
  • 29
  • 44

1 Answers1

2
;WITH a as
(
SELECT
    AID,
    StartTime,
    EndTime,
    StartSSID,
    EndSSID,
    rn = row_number() over (partition by AID,cast(starttime as date) order by case WHEN name = '' or name is null then '20990101' else starttime end, starttime)
    FROM
        #TempTable TT
)
SELECT AID, StartTime, EndTime, StartSSID, EndSSID
WHERE rn = 1
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92