Please help me with an issue that I have come across during work. I’m working with SQL Server, and I’m aware that using cursors I could achieve this, but I’m pretty sure that there is a way of doing it using simple query in SQL, but my brain bulb doesn’t want to turn on. Let me explain my issue with an example.
I have got a table like this:
postedby | date | comment |
1 | 01.01.2012 | sth sth |
2 | 01.01.2012 | sth sth |
3 | 01.01.2012 | sth sth |
2 | 01.01.2012 | sth sth |
3 | 02.01.2012 | sth sth |
2 | 03.01.2012 | sth sth |
2 | 05.01.2012 | sth sth |
What I want to accomplish is get all the posts but one for every user (postedby column), the date must be the latest and of course show the comment.
I have tried doing:
Select distinct postedby, date, comment
but didn’t work, as I understand distinct works for every column, so if in 2 rows postedby is the same but comment is different it will treat it as distincts
I have tried doing:
Select postedby,date,comment group by postedby (don’t bother about the from clause)
giving me the error or aggregation, so I tried
select postedby,min(date) group by postedby – of course works, but I can’t get the comment.
Should I use in some way aggregated queries? Or what am I missing?
Looks like today is the RowNumber function day!!
If all you needed is the latest date and comment for each post: