SQL Server 2008,如何获取另一列更改的某列的值?

时间:2017-08-11 15:30:58

标签: sql sql-server

我正在尝试添加一个名为“更改日期”的字段,我在表格中指出了该字段。我已将表与其他三列一起使用了。如下所示,但我希望得到每份合同最后一次更改的日期。这会涉及某种循环吗?我不知道从哪里开始。日期只是示例,可能是从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

4 个答案:

答案 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)

您可以像这样使用MAXGROUP 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

<强>返回

enter image description here

答案 3 :(得分:0)

您可以使用Windows聚合函数实现此目的。

以下是将返回所需结果的查询。

<a href='$itunesLink'>App Store</a>

DEMO