我想知道在SQL中是否可以只显示一行,然后当该行中的值更改时也显示另一行。例如,我有一个费用表。费用可以添加到订单中。当已经添加的费用更改了费用数量时,原始费用行被标记为已删除,并且新的费用行添加了新的数量。完成此修订后,旧数量将标记为DeletedUnverified(StatusId 20),新费用数量行将以状态为Paid(StatusId 7)进入。然后主管必须验证这些费用变更,因此一旦他们这样做,'deletedUnverified'行的状态将更改为Deleted(StatusId 18),新费用数量行将保持与付费相同。
上图显示了第一次更改费用(前两行)以及主管验证更改后的费用(底部两行)。两个顶行是验证之前的数据(因此statusId = 20是DeletedUnverified)。一旦主管确定,状态将更改为18(已删除)。我想要做的是当费用尚未经过验证时,只显示一个。所以在上图中,顶行,我只想显示行ID 111(StatusId 20)。一旦费用得到验证,我想显示两行,即上面的两行。
我的代码显示了statusID 20行,然后当它更新为statusID 18时,它只显示了StatusId 7行,但我无法得到我想要的内容。我希望这是有道理的。
SELECT
*
FROM
FeeItem sub1
INNER JOIN (
SELECT
ISNULL(b.feeitemid, a.itemid) AS pharmacyformfeeitemid
FROM
(
SELECT
*
FROM
FormFeeItem
WHERE
OrderId IN (1234)
AND StatusId = 7
) a
LEFT JOIN (
SELECT
*
FROM
FormFeeItem
WHERE
OrderId IN (1234)
AND StatusId = 20
) b ON a.OrderId = b.OrderId
) sub2 ON sub1.FeeItemId = sub2.feeitemid
感谢任何帮助......提前感谢:)
答案 0 :(得分:0)
DECLARE @r AS TABLE
(
ID INT
,StatusId INT
,OrderId INT
,Cost MONEY
,NoOfFees INT
)
INSERT INTO @r
VALUES
(111, 20, 1234, -1.2, 3)
,(123, 7, 1234, 2.4, 6)
SELECT r1.*
FROM @r AS r1
LEFT JOIN @r AS r2
ON r1.OrderId = r2.OrderId
AND r2.StatusId = 18
WHERE (r1.StatusId = 7 AND r2.ID IS NOT NULL)
OR
r1.StatusId IN (18, 20)
DELETE @r
INSERT INTO @r
VALUES
(111, 18, 1234, -1.2, 3)
,(123, 7, 1234, 2.4, 6)
SELECT r1.*
FROM @r AS r1
LEFT JOIN @r AS r2
ON r1.OrderId = r2.OrderId
AND r2.StatusId = 18
WHERE (r1.StatusId = 7 AND r2.ID IS NOT NULL)
OR
r1.StatusId IN (18, 20)