need a little help with some sql. I am trying to get distinct frompersonid, but i am wanting to still select all the columns. I am also wanting to end up ordering this by MessageDateTime.
SELECT [MessageID]
,[ToPersonID]
,[FromPersonID]
,[MessageText]
,[MessageDateTime]
,[ViewedByPerson]
FROM dbo.Message
EDIT:
Let me try to clarify this a little better. say i have a table with these values.
messageid toPerson FromPerson text
1 Andy John kdfjskjf
2 Andy John kdfjsdkj
3 Andy Bob kjfksdj
I am wanting to just display last message in the conversation between Andy and John so my results should be
messageid toPerson FromPerson
2 Andy John
3 Andy Bob
You’re obviously using MS SQL Server (or conceivably Sybase). You really don’t need the square brackets; at least to my eyes, they severely limit the readability of the SQL.
Which values do you want to see for a given ‘FromPersonID’?
You can do it this way:
This somewhat arbitrarily picks one value to associate with the given unique ‘FromPersonID’; in general, the values will not come from a single row of data, but you didn’t specify that you wanted some representative row of data – just that you wanted some value from each of the columns.
If you have some criterion in mind for which data should be shown for the cases where the FromPersonID has more than one record, then there are other ways to code the query. However, you may well end up doing a sub-query to identify one message for each FromPersonID (perhaps based on most recent MessageDateTime) and then selecting the row(s) from the main data table that match the FromPersonID and the most recent MessageDateTime for that PersonID: