在SQL中更改了上次日期的值,并更改了上一个日期

时间:2018-01-26 14:15:20

标签: sql date view report

我有一个下面详述的数据表,其中显示了对项目成本的所有更改。

Sub try()
Dim lrow As Long, i As Long
Dim inArr As Variant
Dim oArr() As Variant
With Sheet1

    lrow = 10
    inArr = .Range("B1:C" & lrow).Value
    ReDim oArr(1 To UBound(inArr, 1), 1 To 1)
    For i = LBound(inArr, 1) To UBound(inArr, 1)
        oArr(i, 1) = Application.Sum(Application.Index(inArr, i, 0))
    Next i
    .Range("A1:A" & lrow).Value = oArr

End With

End Sub

我希望报告的结果是显示上一次更改的价值和用户与先前成本的价值。然后是对此的差异。以下是我希望看到的结果。

HistoryID   ItemID  Cost  Date          User
---------------------------------------------
136551      2233    120   2017-06-06    Bren
154021      2233    125   2018-01-26    Admin
136552      2251    89    2017-06-06    Bren
154023      2251    95    2018-01-26    Admin
154026      2251    100   2018-01-29    Manager

1 个答案:

答案 0 :(得分:0)

正如@Gordon Linoff建议的那样,请发布您正在使用的数据库和版本。

这是一个tsql解决方案应该与MSSQL 2008 +

一起使用
declare @example as table (
    ExampleID int not null primary key clustered
,   ItemID int not null
,   Cost    int not null
,   Date_   date not null
,   User_ nvarchar(25) not null
);

insert into @example (ExampleID, ItemID, Cost, Date_, User_)

select 136551, 2233, 120, '2017-06-06', 'Bren' union all
select 154021, 2233, 125, '2018-01-26', 'Admin' union all
select 136552, 2251, 89,  '2017-06-06', 'Bren' union all
select 154023, 2251, 95,  '2018-01-26', 'Admin' union all
select 154026, 2251, 100, '2018-01-29', 'Manager';

 ;with cte as (
    select ExampleID
         , ItemID
         , Cost
         , Date_
         , User_
         , dense_rank() over(partition by ItemID order by exampleid desc) Ranking
      from @example
                )
    , cte2 as (
    select ItemID 
         , [2] PreviousCost
         , [1] CurrentCost
      from (
                select ItemID
                     , Cost
                     , Ranking
                  from cte
                 where ranking < 3
            ) x
     pivot
                (
                    min(cost) for ranking in ([1], [2])
                ) as pvt
            )

select a.ItemID
     , PreviousCost
     , CurrentCost
     , abs(PreviousCost - CurrentCost) CostDifference
     , Date_
     , User_
  from cte a
  join cte2 b
    on a.ItemID = b.ItemID
 where Ranking = 1