Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
How can I select all columns from a subquery that only contains some?

I have the following query:

SELECT id, MAX(`grab_time`) AS `grab_time` FROM events WHERE ended = false GROUP BY id

This returns all the records that have the greatest grab_time as compared to other records that have the same id.

The table events has four columns though, and I want them all. I've been advised to put the above query in to a subquery, in order to get the missing columns (it only shows 2), but I don't know how to do that?

How can I tell sql to basically "SELECT everything WHERE the rows are from the rows in ()"?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can use a correlated subquery:

select e.*
from events e
where not e.ended and
      e.grab_time = (select max(e2.grab_time) from events e2 where e2.id = e.id and not e2.ended);

You want an index on events(id, ended, grab_time) for this query.

Or use row_number():

select e.*
from (select e.*, row_number() over (partition by id order by grab_time desc) as seqnum
      from events e
      where not ended
     ) e
where seqnum = 1;
over 4 years ago · Santiago Trujillo Report

0

You can use the IN as

select * from events 
where (id,grab_time) in
(SELECT id, MAX(`grab_time`) AS `grab_time` FROM events WHERE ended = false GROUP BY id)

You can also use the MAX windows function as follows:

select * from 
(
select t.*, max(grab_time) over (partition by id) as mx
from your_table where ended = false
)
where grab_time = mx
over 4 years ago · Santiago Trujillo Report

0

One approach can be using temporary tables:

   with max_time as
   (
     select id,MAX(grab_time) as grab_time FROM events where ended='false' GROUP BY 
     id
   )
   select * from events e,max_time mt where e.id=mt.id and e.grab_time=mt.grab_time;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!