加入仅包括表中的最大日期 [重复]
Posted
技术标签:
【中文标题】加入仅包括表中的最大日期 [重复]【英文标题】:Join to include only Max Date from Table [duplicate] 【发布时间】:2019-06-29 10:01:00 【问题描述】:我有以下查询,它返回用户 ID、姓名、开始/离开日期和他们离开的日期,他们是公司以前的角色。 我只对他们何时离开上一个角色感兴趣。表 EMPOS 包含每个用户离开每个角色时的数据,因此如果一个人担任 3 个角色,他们将出现在表上 3 次,但我只对最大剩余日期感兴趣
任何帮助将不胜感激
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】:您可以将现有查询嵌套到子查询中并对行进行分组,然后获得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
【讨论】:
以上是关于加入仅包括表中的最大日期 [重复]的主要内容,如果未能解决你的问题,请参考以下文章