Skip to content
Advertisement

Find minimum in one column based on value frrom another column after joinng 2 tables

I’ve searched but can’t find an answer to this one. Any help would be appreciated. I’m running a select statement joining to columns which returns some results but I then want to return the value from one column based on the minimum from another column. Heres what I wrote to get the first set

        select smtm.MediatorID,count(MediatorID) AS aCount 
        from SystemMonitor sm
        join SystemMonitorToMediator smtm
        on sm.SystemMonitorID = smtm.SystemMonitorID
        where sm.RecordStatus = 1 and smtm.Priority = 1 group by smtm.MediatorID

The result I get from this is:

Result

Now I want to return the value 3 from the MediatorID based on the minimum value in the aCount column.

Any ideas?

Advertisement

Answer

Looks like MS SSMS output. Assuming Sql Server.

    select top(1) smtm.MediatorID, count(MediatorID) AS aCount 
    from SystemMonitor sm
    join SystemMonitorToMediator smtm
    on sm.SystemMonitorID = smtm.SystemMonitorID
    where sm.RecordStatus = 1 and smtm.Priority = 1 
    group by smtm.MediatorID
    order by count(MediatorID) ASC
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement