2

我有一个临时表(#TempTable),如下所示:

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

如何在Name上使用 Aggregate 函数,以便当我GROUP BY StartTimeEndTime时我在Name列中得到John Pringle(我尝试使用但它给了我空白值,如果我使用我得到Jeff SmithMIN(Name)MAX(Name)

基本上,我的要求是在列Name中获取第一个可用值

这是我的查询:

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

结果我得到:

AID         StartTime   EndTime     StartSID EndSID     Name

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

我的目标是:

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

谢谢!

4

1 回答 1

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
于 2013-07-17T20:59:23.623 回答