过滤表达式符合条件的选择

时间:2016-02-16 19:58:45

标签: sql postgresql

很少与db进行交互,也没有正式的培训。我想在result.id之后选择符合计算条件的INNER JOIN

results表:

|  id  |  infos_id  |  ...
 00001    99999
 00002    99998
 ...

infos表:

|  info_id  |  counts_id  |  ...
    99999      12345
    99998      12346
    ...

counts表:

|  count_id  |  numerator  |  denom  |  ...
   12345          100         1000
   12346          150         1000
   ...

执行此查询时:

SELECT r.id AS result_id, 
c.count_id AS count_id,
c.numerator/CAST(c.denom AS numeric) * 100 AS freq 
FROM results r INNER JOIN infos i ON r.infos_id = i.info_id 
INNER JOIN counts c ON i.counts_id = c.count_id 
WHERE r.id = 00001;

我得到了这些结果:

 result_id | count_id |          freq          
----------+-----------+------------------------
 00001     |   12345  | 10.0

我想对所有N结果执行此操作,并按freq过滤,当我尝试用WHERE子句替换它时:

WHERE freq < 12.0;

我明白了:

ERROR:  column "freq" does not exist

我可以做一个简单的更改,让我的查询只返回results.id的&lt; {1}}一些给定freq

1 个答案:

答案 0 :(得分:1)

您需要使用WHERE语句中的计算而不是freq的别名。像下面这样的东西应该有效:

SELECT r.id AS result_id, 
c.count_id AS count_id,
c.numerator/CAST(c.denom AS numeric) * 100 AS freq 
FROM results r 
INNER JOIN infos i 
    ON r.infos_id = i.info_id 
INNER JOIN counts c 
    ON i.counts_id = c.count_id 
WHERE c.numerator/CAST(c.denom AS numeric) * 100 < 12