WHERE子句中的CASE或IF语句

时间:2020-03-21 14:07:26

标签: sql

如何在WHERE子句中使用CASE语句或IF语句? 我正在尝试以COUNT为基础申请支票

SELECT * FROM sometable
WHERE CASE WHEN (SELECT COUNT(*) FROM sometable s WHERE SP = 2 AND sometable.id = s.id) > 2 THEN sometable.SP IS NOT NULL END

因此,基本上,如果行数大于1,则应应用IS NOT NULL条件,否则应不这样做。

1 个答案:

答案 0 :(得分:0)

您的逻辑建议如下:

SELECT s.*
FROM (SELECT s.*,
             SUM(CASE WHEN sp = 2 THEN 1 ELSE 0 END) OVER (PARTITION BY id) as cnt_2
      FROM sometable s
     ) s
WHERE cnt_2 <= 2 OR s.sp is not null;

这似乎是等效的。逻辑似乎并不特别有用。