SQL - Select latest max date when NVARCHAR column -
i want select latest input database.
currently gives me comments if i'm filtering using max
simplified version of query
select a.[id], ud.[name], max(convert(date, an.[postedon])) 'date', cast(an.[content] nvarchar(max)) 'comment' [dbo].[account] left join [dbo].[userdata] ud on a.[userid] = ud.userid left join [dbo].[note] on ud.[userid] = an.[customerid] group a.[id], ud.[name], cast(an.[content] nvarchar(max))
current result
+---------+------------------------+------------+-------+ |id |name |date |comment| +---------+------------------------+------------+-------+ |01 |john |2017-08-15 |blue | |01 |john |2017-07-10 |green | |02 |bob |2017-07-15 |green | |02 |bob |2017-06-05 |red | |03 |eric |2017-08-15 |yellow | |04 |karl |2017-08-15 |null | |04 |karl |2017-06-10 |black | +---------+------------------------+------------+-------+
expected/desired result:
+---------+------------------------+------------+-------+ |id |name |date |comment| +---------+------------------------+------------+-------+ |01 |john |2017-08-15 |blue | |02 |bob |2017-07-15 |green | |03 |eric |2017-08-15 |yellow | |04 |karl |2017-08-15 |null | +---------+------------------------+------------+-------+
fyi if remove cast(an.[content] nvarchar(max)) 'comment'
query, don't see 'duplicates' name/id anymore (but no comment then)
any idea?
use row_number()
:
select t.* (select . . ., row_number() on (partition a.id order convert(date, an.[postedon]) desc) seqnum [dbo].[account] left join [dbo].[userdata] ud on a.[userid] = ud.userid left join [dbo].[note] on ud.[userid] = an.[customerid] ) t seqnum = 1;
the . . .
list of columns want.
as note: query not filtering maximum value. query calculating maximum value using aggregation query. important understand difference between filtering , aggregating.
Comments
Post a Comment