给出此表格布局
primary_status | submitted_total_A | total_paid_A | secondary_status | submitted_total_B | total_paid_B
O | 100.00 | 0 | C | 250.00 | 250.00
C | 150.00 | 150.00 | N | 0.00 | 0.00
C | 300.00 | 0 | O | 50.00 | 25.00
O | 400.00 | 50.00 | O | 500.00 | 100.00
我正在尝试获取submitted_total_A-total_paid_A(当primary_status ='O'时)+ Submitted_total_B-total_paid_B(当secondary_status ='O'时)的总和。因此,基本上,当任一状态列包含“ O”时,相关的“ A”和“ B”列都将包含在新列“ row_total”的计算中。
预期结果将是:
*第1行的“行总数”为100.00(仅包括“ A”列的差额)
*第2行的“行总数”将为0.00(两个状态列均不包含“ O”)
*第3行的“行总数”应为25.00(仅包括“ B”列的差额)
*第4行的“行总数”应为750.00(包括“ A”和“ B”列的差)
这是我所拥有的查询,但是我知道该值是错误的,因为当任一状态为“ O”时,“ OR”将同时选择“ A”和“ B”:
SELECT ( submitted_total_a - total_paid_a + submitted_total_b - total_paid_b )
AS
'row_total'
FROM table_1
WHERE primary_status = 'O'
OR secondary_status = 'O';
答案 0 :(得分:2)
SELECT ( CASE
WHEN primary_status = 'O' THEN ( submitted_total_a - total_paid_a )
ELSE 0
END ) +
( CASE
WHEN secondary_status = 'O' THEN ( submitted_total_b - total_paid_b )
ELSE 0
END ) row_total
FROM table
简单地使用CASE WHEN
,它就像[if, else]
个条件块一样工作,例如在PHP中相当于switch/case