查询时是否可以创建虚拟变量
例如,下面的查询只给出满足var1条件的观察结果。我也想要剩下的观察结果,但是上面有一些标签(0/1,指标值就足够了)
+-----+------+--------+------+
| id | Var1 | Var2 | Var3 |
+-----+------+--------+------+
| 345 | 12 | Blue | 3456 |
| 345 | 12 | Red | 2134 |
| 346 | 45 | Blue | 3451 |
| 347 | 25 | yellow | 1526 |
+-----+------+--------+------+
有无
+-----+------+--------+------+--------------------+
| id | Var1 | Var2 | Var3 | Indicator variable |
+-----+------+--------+------+--------------------+
| 345 | 12 | Blue | 3456 | 1 |
| 345 | 12 | Red | 2134 | 0 |
| 346 | 45 | Blue | 3451 | 1 |
| 347 | 25 | yellow | 1526 | 1 |
+-----+------+--------+------+--------------------+
要
{{1}}
答案 0 :(得分:1)
而不是where
中的表达式,您可以在select输出表达式中使用表达式:
=> select a, a = any('{1,2,3,5,7}') as asmallprime
from generate_series(1,10) as a;
a | asmallprime
----+-------------
1 | t
2 | t
3 | t
4 | f
5 | t
6 | f
7 | t
8 | f
9 | f
10 | f
(10 rows)
答案 1 :(得分:1)
Tometzky的答案已经足够,但如果你想要更复杂的东西,你也可以使用CASE陈述。
Tometzky的例子使用带有额外指标的CASE
SELECT a, CASE WHEN a = any('{1,2,3,5,7}') THEN 'YES'
WHEN a = any('{4,9}') THEN 'SQUARE' ELSE 'NO' END as asmallprime
FROM generate_series(1,10) as a;