查询以显示来自另一个 table 的旧值和新值

Query to show old and new values from another table

我在 SQL Server 2012 中有 3 个表。

Table History 是对 Table A 中的值所做的所有更改的历史记录。它可以对 PRICE、LOT、INTEREST 进行许多更改,但在大多数情况下在这种情况下,该值仅更改一次。

Table一个

AID PRICE   LOT INTEREST
------------------------
1   1500    10  0.5
2   2500    20  1.5

Table B

BID AID
--------
11  1
22  2

Table历史。

BID     ChangeField     OldValue    NewValue   ChangeDate
------------------------------------------------------------
11      PRICE           1700        1500       1/1/22
11      LOT             15          10         12/15/21 
11      update_flag                 M          1/1/22

我需要一个查询来显示 Table A 以及来自 Table History 的旧值和新值。如果有超过 1 个更改,则对于旧值,获取最近的先前值。 示例:

AID OldPRICE    NewPRICE    OldLot  NewLot  OldInterest NewInterest
----------------------------------------------------------------
1   1700        1500        15      10      0.5         0.5
2   2500        2500        20      20      1.5         1.5

我该怎么做? 谢谢。

首先,您需要连接所有三个表并按 AID 进行聚合。一旦你有了它,查询需要有选择地从历史中选择值(如果它们存在的话)。

例如:

select
  a.aid,
  max(case when h.changefield = 'PRICE' then coalesce(h.oldvalue, a.price) end) as oldprice,
  max(case when h.changefield = 'PRICE' then coalesce(h.newvalue, a.price) end) as newprice,
  max(case when h.changefield = 'LOT' then coalesce(h.oldvalue, a.lot) end) as oldlot,
  max(case when h.changefield = 'LOT' then coalesce(h.newvalue, a.lot) end) as newlot,
  max(case when h.changefield = 'INTEREST' then coalesce(h.oldvalue, a.interest) end) as oldinterest,
  max(case when h.changefield = 'INTEREST' then coalesce(h.newvalue, a.interest) end) as newinterest 
from table_a a
left join table_b b on b.aid = a.aid
left join history h on h.bid = b.bid
group by a.aid

你可以尝试使用OUTER JOIN条件聚合函数

查询 1:

SELECT A.AID,
       MAX(ISNULL(CASE WHEN h.ChangeField = 'PRICE' THEN h.OldValue END,A.PRICE)) OldPRICE,
       MAX(ISNULL(CASE WHEN h.ChangeField = 'PRICE' THEN h.NewValue END,A.PRICE)) NewPRICE,
       MAX(ISNULL(CASE WHEN h.ChangeField = 'LOT' THEN h.OldValue END,A.LOT)) OldLot,
       MAX(ISNULL(CASE WHEN h.ChangeField = 'LOT' THEN h.NewValue END,A.LOT)) NewLot,
       MAX(ISNULL(CASE WHEN h.ChangeField = 'INTEREST' THEN h.OldValue END,A.INTEREST)) OldInterest,
       MAX(ISNULL(CASE WHEN h.ChangeField = 'INTEREST' THEN h.NewValue END,A.INTEREST)) NewInterest
FROM A 
LEFT JOIN B ON A.AID = B.AID
LEFT JOIN History h ON B.BID = h.BID
GROUP BY A.AID

Results:

| AID | OldPRICE | NewPRICE | OldLot | NewLot | OldInterest | NewInterest |
|-----|----------|----------|--------|--------|-------------|-------------|
|   1 |     1700 |     1500 |     15 |     10 |         0.5 |         0.5 |
|   2 |     2500 |     2500 |     20 |     20 |         1.5 |         1.5 |