Skip to content
Advertisement

How do I get to choose MAX value by result of column?

I have this simple Table about chat Item

enter image description here

I have my query that gets latest entered chat by chatId item as follow

  select MAX(id)
  from ChatItem
  WHERE ChatItem.CaseInvoiceId = 160670

Now I would like to get latest item with isDone = 0 as priority.

If any of result row has isDone = 0, it will get MAX(ID) with isDone = 0. If not, it will get the MAX(ID) with isDone = 1.

Is there any simple and beautiful way to make this?

Advertisement

Answer

How about:

select top 1 id
from ChatItem
where ChatItem.CaseInvoiceId = 160670
order by isdone, id desc

The idea is to order it by isDone in ASC order so 0 should be first (if there is any) and then order it by id in DESC order so MAX value should be on top and then return the top row.

This was written and tested on SQL Server.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement