我正在尝试添加一个名为“更改日期”的字段,我在表格中指出了该字段。我已将表与其他三列一起使用了。如下所示,但我希望得到每份合同最后一次更改的日期。这会涉及某种循环吗?我不知道从哪里开始。日期只是示例,可能是从2007年到现在的任何地方。谢谢你的帮助。
Date Contract Status Change Date
9/30/2015 1 A 6/30/2015
8/31/2015 1 A 6/30/2015
7/31/2015 1 A 6/30/2015
6/30/2015 1 A 6/30/2015
9/30/2015 2 D 8/31/2015
8/31/2015 2 D 8/31/2015
7/31/2015 2 A 6/30/2015
6/30/2015 2 A 6/30/2015
9/30/2015 3 D 9/30/2015
8/31/2015 3 E 8/31/2015
7/31/2015 3 A 6/30/2015
6/30/2015 3 A 6/30/2015
答案 0 :(得分:2)
你可以通过窗口函数看似这样做:
select t.*, min(date) over (partition by contract, status) as change_date
from t;
但问题有点棘手。您想要最近一组类似状态的最早日期。一种方法是使用窗口函数的差异来识别组。然后计算每个组中的最小值,然后计算该值的最大值:
select t.*,
max(group_change_date) over (partition by contract, status) as change_date
from (select t.*,
min(date) over (partition by contract, status) as group_change_date
from (select t.*,
row_number() over (partition by contract order by date) as seqnum_cd,
row_number() over (partition by contract, status order by date) as seqnum_cds,
from t
) t
) t;
答案 1 :(得分:0)
您可以像这样使用MAX
和GROUP BY
:
select MAX([Date]), contract from tbl GROUP BY conrtact
结果:
Date | Contract
===================
9/30/2015 | 1
9/30/2015 | 2
9/30/2015 | 3
答案 2 :(得分:0)
您可以使用窗口函数max()over
示例强>
Select [Date]
,[Contract]
,[Status]
,[Change Date] = max([Date]) over (Partition By [Contract])
from YourTable
<强>返回强>
答案 3 :(得分:0)