请告诉我这个问题。
TABLE:PPP
+-------+---------+---------+----------+
|No | Flag_A | Flag_B | Qty |
+-------+---------+---------+----------+
|100 | P | 0 | 10 |
|300 | B | 1 | 20 |
|500 | C | 0 | 30 |
|100 | P | 0 | 40 |
|100 | P | 0 | 50 |
|300 | B | 1 | 60 |
|500 | C | 1 | 70 |
|100 | P | 0 | 80 |
|500 | B | 2 | 90 |
+-------+---------+---------+----------+
SELECT NO, SUM(QTY) AS QTY
FROM PPP
WHERE
CASE FLAG_B IN (
WHEN FLAG_A = 'P' THEN '0'
WHEN FLAG_A = 'C' THEN '1'
WHEN FLAG_A = 'B' THEN '0' , '1' <- how to write?
END
)
GROUP BY NO
我想得到这个结果。
+----+-----+
| No | Qty |
+----+-----+
| 100| 180|
| 300| 80|
| 500| 100|
+----+-----+
我应该写什么sql?
用布尔逻辑来说,这会更简单:
where (flag_a = 'P' and flag_b = 0)
or (flag_a = 'C' and flag_b = 1)
or (flag_a = 'B' and flag_b in (0, 1))
我们可以进行一点因子分解:
where (flag_a in ('B', 'P') and flag_b = 0)
or (flag_a in ('B', 'C') and flag_b = 1)
或者我们可以使用元组相等:
where (flag_a, flag_b) in (('P', 0), ('C', 1), ('B', 0), ('B', 1))
flag_b
看起来像一个数字,所以我将它与字面数字进行了比较;如果这真的是一个字符串,那么您可以在文字周围加回单引号。
对于flag_a='B'
的情况,使用包含CASE..WHEN
表达式的DECODE()
函数可能是获得所需结果(如(的替代方法
SELECT no, SUM(qty) AS qty
FROM ppp
WHERE DECODE(flag_a,'P',0,'C',1,'B', CASE WHEN flag_b IN (0,1) THEN flag_b END)=flag_b
GROUP BY no
演示
p.S:我认为No=500
的数据存在问题,需要解决