是否可以根据“案例值”创建选择。在下面的例子中Category
。假设我想获得Low
值。我使用WHERE Category = 'Low'
时会引发错误,因为列Category
不存在。
我知道我可以通过将WHERE Category = 'Low'
替换为Where digit > 0 AND digit <=40
来创建选择。但这似乎是一种不好的方式,因为这是双重表达。
SELECT digits,
CASE
When digit > 0 AND digit <=40 THEN 'Low'
When digit > 40 AND digit <=75 THEN 'Average'
When digit > 75 THEN 'High'
END AS Category
FROM digits_table
WHERE Category = 'Low'
答案 0 :(得分:2)
您可以使用with语句:
WITH tmp as (
SELECT digits,
CASE
When digit > 0 AND digit <=40 THEN 'Low'
When digit > 40 AND digit <=75 THEN 'Average'
When digit > 75 THEN 'High'
END AS Category
FROM digits_table
)
select * from tmp where category = 'Low'
答案 1 :(得分:1)
或(旧skool):
SELECT * FROM (
SELECT digits,
CASE
When digit > 0 AND digit <=40 THEN 'Low'
When digit > 40 AND digit <=75 THEN 'Average'
When digit > 75 THEN 'High'
END AS Category
FROM digits_table
) AS tmp WHERE Category = 'Low'
答案 2 :(得分:1)
使用PSQL 9.2+,您可以使用Range types和Range functions and operators
select * from digits_table where digits <@ int4range(0, 40, '(]');
考虑下表:
postgres=# select * from tests;
id | digit
----+-------
1 | 10
2 | 20
3 | 30
4 | 40
您可以查询(请注意,int4range底部绑定是包含,而上限是独占 ):
postgres=# select * from tests where digit <@ int4range(20,40);
id | digit
----+-------
2 | 20
3 | 30
当然,您可以将字符串转换为所需的输入/排除模式(只需按照通常在数学类中的方式放下,然后转换为范围类型):
postgres=# select * from tests where digit <@ '(20,40]'::int4range;
id | digit
----+-------
3 | 30
4 | 40
postgres=# select * from tests where digit <@ '[20,40]'::int4range;
id | digit
----+-------
2 | 20
3 | 30
4 | 40
有一种更简单明了的方法来控制边界(这是PostgreSQL,宝贝!):
postgres=# select * from tests where digit <@ int4range(20,40,'[]');
id | digit
----+-------
2 | 20
3 | 30
4 | 40
postgres=# select * from tests where digit <@ int4range(20,40,'()');
id | digit
----+-------
3 | 30
postgres=# select * from tests where digit <@ int4range(20,40,'[)');
id | digit
----+-------
2 | 20
3 | 30