Using ORDER BY and GROUP BY together

前端 未结 7 1870
清酒与你
清酒与你 2020-11-28 05:30

My table looks like this (and I\'m using MySQL):

m_id | v_id | timestamp
------------------------
6    |   1  | 1333635317
34   |   1  | 1333635323
34   |            


        
相关标签:
7条回答
  • 2020-11-28 05:39

    One way to do this that correctly uses group by:

    select l.* 
    from table l
    inner join (
      select 
        m_id, max(timestamp) as latest 
      from table 
      group by m_id
    ) r
      on l.timestamp = r.latest and l.m_id = r.m_id
    order by timestamp desc
    

    How this works:

    • selects the latest timestamp for each distinct m_id in the subquery
    • only selects rows from table that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)
    • orders the rows
    0 讨论(0)
  • 2020-11-28 05:40

    SQL>

    SELECT interview.qtrcode QTR, interview.companyname "Company Name", interview.division Division 
    FROM interview 
    JOIN jobsdev.employer 
        ON (interview.companyname = employer.companyname AND employer.zipcode like '100%')
    GROUP BY interview.qtrcode, interview.companyname, interview.division
    ORDER BY interview.qtrcode;
    
    0 讨论(0)
  • 2020-11-28 05:42

    Here is the simplest solution

    select m_id,v_id,max(timestamp) from table group by m_id;
    

    Group by m_id but get max of timestamp for each m_id.

    0 讨论(0)
  • 2020-11-28 05:46

    If you really don't care about which timestamp you'll get and your v_id is always the same for a given m_i you can do the following:

    select m_id, v_id, max(timestamp) from table
    group by m_id, v_id
    order by timestamp desc
    

    Now, if the v_id changes for a given m_id then you should do the following

    select t1.* from table t1
    left join table t2 on t1.m_id = t2.m_id and t1.timestamp < t2.timestamp
    where t2.timestamp is null
    order by t1.timestamp desc
    
    0 讨论(0)
  • 2020-11-28 05:49

    Just you need to desc with asc. Write the query like below. It will return the values in ascending order.

    SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;
    
    0 讨论(0)
  • 2020-11-28 05:59

    Why make it so complicated? This worked.

    SELECT m_id,v_id,MAX(TIMESTAMP) AS TIME
     FROM table_name 
     GROUP BY m_id
    
    0 讨论(0)
提交回复
热议问题