Skip to content
Advertisement

How to join 2 DB tables and perform GROUP BY at the same time?

I have 2 tables:

Equipment(PK int id,nvarchar name)

EquipmentAction(int EquipmentId, datetime Timestamp)

I want to display the earliest Timestamp for each named Equipment and I cannot figure it out.

  • I can do select EquipmentId, min(TimeStamp) from EquipmentAction group by(EquipmentId)
  • I can do select e.name, a.TimeStamp from Equipment e inner join EquipmentAction a on e.id=a.EquipmentId

But I can’t see how to combine these two ideas.

Advertisement

Answer

You can just add the group by, like this:

select e.name, min(a.TimeStamp)
from Equipment e inner join
     EquipmentAction a
     on e.id = a.EquipmentId
group by e.name
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement