我必须查询表格以搜索给定的条件:
范围中指定的order_no必须存在。
示例:我收到一个order_no:003 - 007范围的请求。所以,我想检查范围内提到的所有order_no是否存在。如果不存在则返回false。
ALL order_no的order_status必须为1.如果不存在则返回false。
Order_string Order_no Order_status
ABE 1 1
ABE 2 1
ABE 3 0
PSB 4 0
PSB 5 1
PSB 6 0
REL 7 0
REL 8 1
REL 9 1
REL 10 1
我正在尝试EXIST和BETWEEN但无法查询数据库。
答案 0 :(得分:4)
您应该检查以下条件:
count(order_no) = count(distinct order_no) -- order_no are distinct in the range
and count(*) = end_val- start_vat+ 1 -- number of rows equals to size of the range
and bool_and(order_status::bool) -- all order_status are 1
如果列是唯一的,则不需要第一个条件。
您可以在函数中执行此操作:
create or replace function check_range(int, int)
returns boolean language sql as $$
select
count(order_no) = count(distinct order_no)
and count(*) = $2- $1+ 1
and bool_and(order_status::bool)
from my_table
where order_no between $1 and $2;
$$;
答案 1 :(得分:0)
如果我理解你的问题是正确的,那么如果3 {7之间的ORDER_STATUS
ORDER_NO
中至少有一个是0,那么你想要错误
SELECT
CASE WHEN Z.SUM_STATUS > 0 THEN 'FALSE' ELSE 'TRUE' END AS RESULT
FROM
(SELECT
SUM(CASE WHEN (ORDER_NO BETWEEN 3 AND 7) AND (ORDER_STATUS = 0) THEN 1 ELSE 0 END) AS SUM_STATUS
FROM YOUR_TABLE) Z;
答案 2 :(得分:0)
尝试:您可以使用此概念,如果它将返回1然后TRUE
其他FALSE
SELECT 1
FROM tmp t
WHERE Order_no BETWEEN 003 AND 007
AND Order_status = 1
HAVING COUNT(*) = (007-003)+1