我正在处理任务历史记录并尝试查找附加到同一记录的两个日期:1)最近一次任务被批准(最大批准); 2)批准后的第一个提交日期。
这是我到目前为止所做的:
Select
a.assn_uid,
max(b.ASSN_TRANS_DATE_ENTERED) as LastApprove,
e.LastSubmitted
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] a
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] b
on a.ASSN_TRANS_UID = b.ASSN_TRANS_UID
join (select c.assn_uid,
min(d.ASSN_TRANS_DATE_ENTERED) as LastSubmitted
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] c
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] d
on c.ASSN_TRANS_UID = d.ASSN_TRANS_UID
where c.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and d.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 0
group by c.assn_uid ) e
on e.ASSN_UID = a.ASSN_UID
where a.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and b.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 1
group by a.assn_uid, e.LastSubmitted
这很接近,但是,它第一次给我提交任务。我确信我需要使用另一个子查询,我只是不知道如何在同一结果中引用一个列。
这是任务历史。突出显示的是我试图展示的两个日期:
答案 0 :(得分:0)
我不知道我可以在任何合理的时间内浏览您的查询,但要在特定行之后获取行,您需要执行以下操作:
create table #submissions (
ID int,
DateAdded datetime,
SubmissionType nvarchar(100)
)
insert #submissions values
(1, '2010-01-01', 'first ever'),
(1, '2010-01-02', 'second'),
(1, '2010-01-03', 'third'),
(1, '2010-01-04', 'approve'),
(1, '2010-01-05', 'first after approve'),
(1, '2010-01-06', 'second after approve'),
(1, '2010-01-07', 'third after approve')
declare @lastApprovalDate datetime
select @lastApprovalDate = MAX(DateAdded)
from #submissions
where
SubmissionType = 'approve'
declare @firstAfterApprovalDate datetime
select @firstAfterApprovalDate = MIN(DateAdded)
from #submissions
where
DateAdded > @lastApprovalDate
select *
from #submissions
where
DateAdded = @firstAfterApprovalDate
drop table #submissions
一般情况下,使用MAX()获取最后一个批准日期,然后使用MIN()获取该日期之后的第一个日期,其中DateAdded>最大,然后选择该日期的行。我添加了Top 1,以防万一在那时碰巧有多行。不确定您的数据是否可行,但只是为了安全。
答案 1 :(得分:0)
在一些帮助下,我们发现我们需要额外的一分钟来处理查询。
SELECT
final.assn_uid,
final.LastApprove,
min(final.SubmissionDate) FirstSubmitted
FROM
(Select
a.assn_uid,
max(b.ASSN_TRANS_DATE_ENTERED) as LastApprove,
e.SubmittedDates SubmissionDate
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] a
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] b
on a.ASSN_TRANS_UID = b.ASSN_TRANS_UID
join (select c.assn_uid,
(d.ASSN_TRANS_DATE_ENTERED) as SubmittedDates
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] c
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] d
on c.ASSN_TRANS_UID = d.ASSN_TRANS_UID
where c.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and d.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 0
) e
on e.ASSN_UID = a.ASSN_UID
where a.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and b.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 1
and e.SubmittedDates > b.ASSN_TRANS_DATE_ENTERED
group by a.assn_uid, e.SubmittedDates) Final
GROUP BY
final.assn_uid,
final.LastApprove