Skip to content
Advertisement

How to apply max function in a join query?

I am new to SQL Server, I have 3 tables consider an employee table

empid name location
1 abc USA
2 efg UK

Another table named location-table

location holidaycode
uk uk1
usa usa1

And also holidaytable:

holiday-code date type
uk1 2022-01-01 LM
uk1 2022-01-01 RMC

Expected result is:

empid location holidaycode date type 1
2 uk uk1 2022-01-01 RMC

suppose I query the tables based on empid and date say ,the holidays available for empid 2 from a particular from date such that on a particular day (2022-01-01) I have LM and RMC on that day , I need only RMC ,if RMC is not available else LMC.

Advertisement

Answer

Please try this

select e.empid, e.location, h.holidaycode, [date], max([type])
from employee e inner join location_table l 
                           on e.location=l.location
                inner join holidaytable h 
                           on l.holidaycode=h.holidaycode
where e.empid=2 and h.[date]='2022-01-01'
group by e.empid, e.location, h.holidaycode, [date]

Example:

Schema and insert statements:

   create table employee(empid int, name varchar(50), location varchar(50));
   insert into employee values(1,   'abc',  'USA');
   insert into employee values(2,   'efg',  'UK');
   
   create table location_table(location varchar(50),holidaycode varchar(50));
   insert into location_table values('uk','uk1');
   insert into location_table values('usa','usa1');
   
   create table holidaytable(holidaycode    varchar(50), [date] date, [type] varchar(50));
   insert into holidaytable values('uk1',   '2022-01-01',   'LM');
   insert into holidaytable values('uk1',   '2022-01-01',   'RMC');
  

Query:

 select e.empid, e.location, h.holidaycode, [date], max([type]) [type 1]
   from employee e inner join location_table l 
                              on e.location=l.location
                   inner join holidaytable h 
                              on l.holidaycode=h.holidaycode
   where e.empid=2 and h.[date]='2022-01-01'
   group by e.empid, e.location, h.holidaycode, [date]

Output:

empid location holidaycode date type 1
2 UK uk1 2022-01-01 RMC

db<>fiddle here

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