联接以仅包括表中的最大日期

时间:2019-02-05 14:42:52

标签: sql-server

我有以下查询,该查询返回用户ID,名称,开始/离开日期和他们离开公司之前的日期。 我只对他们何时离开上一个职位感兴趣。表格EMPOS包含每个用户离开每个角色时的数据,因此,如果一个人拥有3个角色,他们将在表格中出现3次,但我只对最晚离开日期感兴趣

任何帮助将不胜感激

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] 

1 个答案:

答案 0 :(得分:1)

您可以将现有查询嵌套到子查询中,并对行进行分组,然后获得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

让我展示一下GROUPING并使用MAX函数的基本概念:

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

输出:

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