سؤال

I have a following db format set up:

id  fid     name    time    flag
1   224     Mike    112     3
2   555     John    98      5
3   224     Mike    101     0
4   121     Ann     80      1
5   224     Mike    55      7
6   121     Ann     150     4

I used following query to sort and display them grouped by fid (or name) and to sort them by lowest time:

SELECT id, fid, name, MIN(time), flag FROM dblist GROUP BY name ORDER BY MIN(time)

This works fine as I get the output in order I want. Something like:

name    time
Mike    55
Ann     80
John    98

However, if I try to display fid, flag, or any other fields that are associated with that particular time record I get some other values (presumably first that query comes across).

What I would like to get is following format:

id  fid     name    time    flag
5   224     Mike    55      7
4   121     Ann     80      1
2   555     John    98      5

I am wondering if there is a way to get this done with just one database and some other query syntax?

Thanks.

هل كانت مفيدة؟

المحلول

Use a self join on two conditions 1 with name and with the minimum of time score for each name,group by results are indeterminate their order is not guaranteed with the latest or the first record in group

select t.* from t
join (SELECT name, MIN(`time`) `time`
 FROM t GROUP BY name) t1
on(t.name = t1.name and t.`time`=t1.`time`)
order by t.`time` 

Demo

نصائح أخرى

use this request

SELECT
    id,
    fid, 
    name, 
    MIN(time), 
    flag 
FROM 
    dblist 
GROUP BY
    id, 
    fid, 
    name 
ORDER BY 
    MIN(time)

Query:

SQLFIDDLEExample

SELECT t.id, 
       t.fid, 
       t.name, 
       t.time, 
       t.flag
FROM t t
  LEFT JOIN t t1
    ON t.fid = t1.fid
    AND t.time > t1.time
WHERE t1.time is null

Result:

| ID | FID | NAME | TIME | FLAG |
|----|-----|------|------|------|
|  2 | 555 | John |   98 |    5 |
|  4 | 121 |  Ann |   80 |    1 |
|  5 | 224 | Mike |   55 |    7 |
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top