SQL 在 where 子句中使用 case when 过滤
SQL Filtering using case when in where clause
我需要排除下面 table 中的最后一行:
dim11 dim12 amount1
NULL 1 200
NULL 2 300
Y 3 100
N 3 100
我想得到 amount1 的总和,其中 dim12 在 (1,2,3) 中,但只有 dim12 =3 有 dim 11 = 'Y' 不在 = 'N'.
SELECT
SUM(AMOUNT1)
FROM table1
WHERE dim12 in (1,2,3)
总结:我想排除所有 dim12 = 3 和 dim11 <> 'Y'
Current Output: 700
Expected Output: 600
我需要在 Where 子句中使用 CASE 吗?提前谢谢你。
where dim12 in (1,2,3) but only dim12 =3 having dim 11 = 'Y' not in = 'N'.
这听起来像:
where dim12 in (1, 2) or (dim12 = 3 and dim11 = 'Y')
如果你想要一个条件总和——比如因为你还有其他列——那么使用:
select sum(case when dim12 in (1, 2) or dim11 = 'Y' then amount end)
from t
where dim12 in (1, 2, 3)
我需要排除下面 table 中的最后一行:
dim11 dim12 amount1
NULL 1 200
NULL 2 300
Y 3 100
N 3 100
我想得到 amount1 的总和,其中 dim12 在 (1,2,3) 中,但只有 dim12 =3 有 dim 11 = 'Y' 不在 = 'N'.
SELECT
SUM(AMOUNT1)
FROM table1
WHERE dim12 in (1,2,3)
总结:我想排除所有 dim12 = 3 和 dim11 <> 'Y'
Current Output: 700
Expected Output: 600
我需要在 Where 子句中使用 CASE 吗?提前谢谢你。
where dim12 in (1,2,3) but only dim12 =3 having dim 11 = 'Y' not in = 'N'.
这听起来像:
where dim12 in (1, 2) or (dim12 = 3 and dim11 = 'Y')
如果你想要一个条件总和——比如因为你还有其他列——那么使用:
select sum(case when dim12 in (1, 2) or dim11 = 'Y' then amount end)
from t
where dim12 in (1, 2, 3)