tsql nesting subquery - group by last entry by week

Soldato
Joined
8 Mar 2005
Posts
3,860
Location
London, UK
I have a table with with a number of records but the key columns are UTCDate, USER and APPName.

Code:
SELECT        *, DATEPART(week, utcDate) AS WEEKNO
FROM            (SELECT        *, row_number() OVER (partition BY user, AppName
                          ORDER BY utcDate DESC) AS rn
FROM            dbo.sometable) a
WHERE        a.rn = 1
This returns the last entry for each user for each AppName. However, I would like to return the last entry for each user for every week. Nesting another subquery is the part which is confusing me. Any pointers much appreciated.

TIA!
 
I can't believe it was that obvious! there's me thinking I needed another subquery within the partition!
Code:
SELECT        *, DATEPART(week, utcDate) AS WEEKNO
FROM            (SELECT        *, row_number() OVER (partition BY user, AppName, DATEPART(week, utcDate)
                          ORDER BY utcDate DESC) AS rn
FROM            dbo.sometable) a
WHERE        a.rn = 1
 
Back
Top Bottom