简体   繁体   中英

SQL Query with MAX and CASE WHEN

I have the following SQL query and its output is as shown below:

select stds.classID as classID, stds.clsLimit as clsLimit
  , max(stds.id)as maxStdsID  
from class cls 
left outer join students stds
on cls.id = stds.classID
group by stds.classID,stds.clsLimit

在此处输入图片说明

For each classID, I want to pick the max of maxStdsID which has clsLimit as 1. If there is no maxStdsID that has clsLimit as 1, then I would want to pick the max of maxStdsID which has clsLimit as 0

I tried the same with the below logic

select stds.classID as classID
  , max(CASE WHEN stds.clsLimit = 1 then stds.id else stds.id end) as maxStdsID  
from class cls 
left outer join students stds
on cls.id = stds.classID
group by stds.classID

I am not getting the desired output.

You are close . . . but use coalesce() :

select cls.classID,
       coalesce(max(case when stds.clsLimit = 1 then stds.id end),
                max(case when stds.clslimit = 0 then stds.id end)
               ) as maxStdsID  
from class cls left outer join
     students stds
     on cls.id = stds.classID
group by cls.classID;

If there is no value for "1", then this picks up the maximum value for "0".

Note that I changed the aggregation column to use the column from the first table in the left join , rather than the second table.

You might try:

select stds.classID as classID ,  stds.clsLimit as clsLimit , 
max(stds.id)as maxStdsID  
from class cls 
left outer join students stds
on cls.id = stds.classID
where stds.clsLimt = CASE WHEN stds.clsLimit = 1 then 1 ELSE 0 END
group by stds.classID,stds.clsLimit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM