3

我有一个查询,我需要在其他查询中使用查询结果。所以,我使用了“WITH .. As”。问题是临时变量应该是整数,而它是自动以文本数据类型创建的。我如何更改或修改代码以具有整数数据类型的变量。

WITH A as (
SELECT ambtemp,
       date_trunc('hour', dt)+
       CASE WHEN date_part('minute', dt) >= 30
            THEN interval '30 minutes'
            ELSE interval '0 minutes'
       END as t
FROM temm),

B as(
SELECT ambtemp,t,

       max(ambtemp) OVER (PARTITION BY t) as max_temp,
       min(ambtemp) OVER (PARTITION BY t) as min_temp
FROM A)
SELECT *

FROM B
WHERE (max_temp - min_temp) <= 0.2

max_temp 和 min_temp 应该以整数数据类型构建,而它们是文本格式。

4

2 回答 2

4

谢谢,@Igor Romanchenko

WITH A as (
SELECT ambtemp,
       date_trunc('hour', dt)+
       CASE WHEN date_part('minute', dt) >= 30
            THEN interval '30 minutes'
            ELSE interval '0 minutes'
       END as t
FROM temm),

B as(
SELECT ambtemp,t,

       max(ambtemp::float(23)) OVER (PARTITION BY t) as max_temp,
       min(ambtemp::float(23)) OVER (PARTITION BY t) as min_temp
FROM A)
SELECT *

FROM B
WHERE (max_temp - min_temp) <= 0.2
于 2012-11-26T18:32:08.100 回答
2

为了更改类型,您需要使用::运算符对其进行转换。因此,要将整数转换为字符串,您可以这样做myCol::Text

在您的特定情况下,您正在做相反的事情:

 max(ambtemp) OVER (PARTITION BY t) as max_temp::int,
 min(ambtemp) OVER (PARTITION BY t) as min_temp::int

您可能想通过以下方式检查空值:

NULLIF(your_value, '')::int

我也会对不可转换为整数的值持谨慎态度。

有关强制转换和类型的更多信息,请参阅PostgreSQL 文档

于 2012-11-26T15:48:30.567 回答