I have the following table
| ID | Name | CodSituation |
| ------------ | ------------ | ------------ |
| 1 | John | 1 |
| 2 | Mary | 2 |
| 3 | Mary | 3 |
| 4 | Mary | 4 |
| 5 | John | 5 |
| 6 | John | 2 |
| 7 | Mary | 1 |
I want to select the Names, ID's and CodSituation for all users where their last entry is CodSituation=2
In these results I will get just the id 6 As Mary's last entry was CodeSituation=4 if more than one users have their latest CodSituation=2 I want them too.
3条答案
按热度按时间b1payxdu1#
[FINAL EDIT] After seeing what was posted at the end of this answer I figured out that the user was asking the wrong question:
What they were asking was 'show me everyone who has CodSituation=2' when they meant 'Show me all the users who's last entry in CodSituation field=2'
Here is the correct query for that:
Here is the fiddle for that: http://sqlfiddle.com/#!2/a731d [END]
[here are the previous queries, for reference] Looks to me like you just need:
To get all of the people with situation 2
To get only the last entry using mysql:
To get the last entry using sql-server:
See a working example here:
http://sqlfiddle.com/#!6/022fb/4
[edit]
OP supplied an actual dataset:
This shows all the unique users with a CodSituation of 2 (with one entry per person)
http://sqlfiddle.com/#!3/be404/2
mv1qrgav2#
Can be achieved like this, but may not be the best way to do this
Basically what I am doing is Create a temporary table and add the Name and Maximum row number.
Which then match again that the maximum row number row is associated with CodSituation=2
Fiddle Sample
umuewwlo3#
I found an easier way concatenating fieds and using max solve this problem... Thanks!
http://sqlfiddle.com/#!3/3dc1c/10