我有一个表,我想在其中有条件地根据另一个行值计算一些行值。
表格如下所示
LevelID StepID Amt Type BItem PItem
-------------------------------------------------
6 3 18000 Fixed BS
6 3 10 Percent BS UA
6 3 10 Percent BS TA
6 3 3.5 Percent BS Tx
7 3 24000 Fixed BS
7 3 10 Percent BS UA
7 3 10 Percent BS TA
7 3 3.5 Percent BS Tx
目的是计算行的Amt值Type
='百分比',其中Bitem = PItem,LevelID和StepID对于BItem和PItem都是相同的
因此示例输出将是
LevelID StepID Amt Type BItem PItem Total
----------------------------------------------------------
6 3 18000 Fixed BS 18,000
6 3 10 Percent BS UA 1,800
6 3 10 Percent BS TA 1,800
6 3 3.5 Percent BS Tx 630
7 3 24000 Fixed BS 24,000
7 3 10 Percent BS UA 2,400
7 3 10 Percent BS TA 2,400
7 3 3.5 Percent BS Tx 840
我一直在尝试不同的SQL语句,但还没有任何合理的输出
答案 0 :(得分:1)
要查找值,请使用correlated subquery:
SELECT *,
CASE Type
WHEN 'Fixed' THEN Amt
ELSE (SELECT B.Amt * ATable.Amt / 100
FROM ATable AS B
WHERE B.Type = 'Fixed'
AND B.LevelID = ATable.LevelID
AND B.StepID = ATable.StepID
AND B.PItem = ATable.BItem)
END AS Total
FROM ATable;