• Scanning the nonclustered index, there is an implied first key on the partition ID, so the following can use a Stream Aggregate:

    SELECT sessionid, username

    FROM dbo.AttemptedLogin

    WHERE sessionid IS NOT null

    GROUP BY $Partition.PartitionByYear([DateTime]), UserName, SessionID

    Similarly, if a single partition is statically specified, the following also results in a Stream Aggregate, since the keys of the nonclustered index are (UserName, SessionID):

    SELECT SessionID, UserName FROM dbo.AttemptedLogin

    WHERE $Partition.PartitionByYear([DateTime]) = 1 AND SessionID IS NOT null

    GROUP BY UserName, SessionID

    The problem in the original code is that it adds UserID to the mix, and fails to use a Stream Aggregate:

    SELECT UserId, SessionID, UserName FROM dbo.AttemptedLogin

    WHERE $Partition.PartitionByYear([DateTime]) = 1 AND SessionID IS NOT null

    GROUP BY UserId, UserName, SessionID

    Now UserID forms part of the key of the nonclustered index since it is not declared as unique, but it comes after the nonclustered keys. Writing the GROUP BY clause to reflect the key order results in the Stream Aggregate you are looking for:

    SELECT UserId, SessionID, UserName FROM dbo.AttemptedLogin

    WHERE $Partition.PartitionByYear([DateTime]) = 1 AND SessionID IS NOT null

    GROUP BY UserName, SessionID, UserId

    Should the order of the GROUP BY keys matter? No. In that sense, it is a limitation, in the same way that writing a query with several window functions might result in an unnecessary sort depending on the written order of the query.

    It may be more natural (and easier for future maintenance) if you explicitly include UserID in the nonclustered index definition.

    edit: In response to your other Twitter question, yes the same considerations apply to DISTINCT:

    -- Sort

    SELECT DISTINCT UserId, UserName, SessionID FROM dbo.AttemptedLogin

    WHERE $Partition.PartitionByYear([DateTime]) = 1 AND sessionid IS NOT null

    -- No sort

    SELECT DISTINCT UserName, SessionID, UserId FROM dbo.AttemptedLogin

    WHERE $Partition.PartitionByYear([DateTime]) = 1 AND sessionid IS NOT null

    Another option is to keep the GROUP BY or DISTINCT column order as it is, and add a presentation ORDER BY UserName, SessionID, UserId