0

I have the below query which returns users IDs,Names,Start/Leaving Date and Date they left they're previous role within the company. I am only interested in when they left the last previous role. table EMPOS has the data in when each user left each role so if a person has been in 3 roles they'll appear on the table 3 times however im only interested in the max left date

Any help would be appreciated

enter image description here

select cast(a.DET_NUMBER as varchar) as 'Frontier ID', CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) as 'Name',
CASE WHEN b.TER_DATE <GETDATE() THEN '_'+CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) ELSE CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) END AS 'Name2',
cast(a.DET_DATE_JND as date) as 'Start Date', cast(b.TER_DATE as date) as 'Leaving Date',
case when c.POS_END = '0001-01-02' then null else c.POS_END end as 'Date User Left Prev Role'

from EMDET a
left outer join EMTER b on a.DET_NUMBER = b.DET_NUMBER
left outer join EMPOS c on a.DET_NUMBER = c.DET_NUMBER
left outer join EMDET d on c.POS_MANEMPNO = d.DET_NUMBER


where b.TER_DATE is null and c.POS_END >'1900-01-01'

order by [Leaving Date] 
0

1 Answer 1

1

You can nest your existing query into subquery and group the rows and then get MAX of DateUserLeftPrevRole:

select
  q.FrontierID
, q.Name
, q.Name2
, q.StartDate
, q.Leaving Date
, MAX(q.DateUserLeftPrevRole)
from
(
    select 
    cast(a.DET_NUMBER as varchar) as FrontierID
   , CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) as Name
   ,CASE WHEN b.TER_DATE <GETDATE() THEN '_'+CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) 
       ELSE CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) END AS 'Name2'
   ,cast(a.DET_DATE_JND as date) as 'StartDate'
   , cast(b.TER_DATE as date) as 'LeavingDate'
   , case when c.POS_END = '0001-01-02' then null else c.POS_END end as 'DateUserLeftPrevRole'

    from EMDET a
    left outer join EMTER b on a.DET_NUMBER = b.DET_NUMBER
    left outer join EMPOS c on a.DET_NUMBER = c.DET_NUMBER
    left outer join EMDET d on c.POS_MANEMPNO = d.DET_NUMBER
    where b.TER_DATE is null and c.POS_END >'1900-01-01'
 )q
 GROUP BY q.FrontierID, q.Name, q.Name2, q.StartDate, q.Leaving Date

Let me show a basic idea of of GROUPING and using MAX function:

DECLARE @TestTable TABLE 
(
    Col1 VARCHAR(10),
    Col2 INT,
    Col3 INT
)

INSERT INTO @TestTable
(
    Col1,
    Col2,
    Col3
)
VALUES
 ('A',         10,       20)
,('A',         11,       30)
,('A',         12,       40)
,('A',         12,       60)

SELECT 
  tt.Col1
, tt.Col2
, MAX(tt.Col3) MaxCol3
FROM @TestTable tt 
GROUP BY tt.Col1, tt.Col2

OUTPUT:

Col1    Col2     MaxCol3
 A       10        20
 A       11        30
 A       12        60

Not the answer you're looking for? Browse other questions tagged or ask your own question.