sql - 使用列别名在 PostgreSQL 中进行操作时出错

标签 sql postgresql

我在查询时遇到问题。我想对我的薪资系统进行操作。我这是我的查询,它不起作用。

查询:

select
    hrrawd_timein,
    hrrawd_shiftin,
    (
      (extract(hour from (hrrawd_timein::time))
      - extract(hour from (hrrawd_shiftin::time))
      )::numeric
    ) AS shiftinhours,
    (
      (extract(minute from (hrrawd_timein::time))
      - extract(minute from (hrrawd_shiftin::time))
      )::numeric
    ) AS shiftinminutes,
    (
      ((extract(hour from (hrrawd_timein::time))
      - extract(hour from (hrrawd_shiftin::time)
      ))*60)::numeric
    )
    + 
    (
      (extract(minute from (hrrawd_timein::time))
      - extract(minute from (hrrawd_shiftin::time))
      )::numeric
    ) AS Total,
    case
      when (Total >0) then 'Late' 
      else 'EARLY'
    end as remarks
  FROM hr.hrrawd;

错误:

> ERROR:  column "total" does not exist LINE 7: case when (Total >0)
> then 'Late'

最佳答案

我建议使用 common table expressions当您需要预先计算的列时:

with cte1 as (
    select
        hrrawd_timein, hrrawd_shiftin,
        (
           extract(hour from (hrrawd_timein::time)) -
           extract(hour from (hrrawd_shiftin::time))
        )::numeric as shiftinhours,
        (
           extract(minute from (hrrawd_timein::time)) -
           extract(minute from (hrrawd_shiftin::time))
        )::numeric as shiftinminutes
    from hr.hrrawd
), cte2 as (
    select
        *,
        shiftinhours * 60 + shiftinminutes as [total]
   from cte1
)
select
    *,
    case when [total] > 0 then 'Late' else 'Early' end as remarks
from cte2

我认为它比子查询更简洁。您还可以根据需要链接任意数量的 CTE,它可以帮助您保持 DRY principle - 请注意 shiftinminutesshiftinhours 是如何只计算一次而不是两次的。可读性很重要,不要重复计算,以后很难维护。

顺便说一句,看看interval data type in PostgreSQL , 你可以从中提取小时和分钟

关于sql - 使用列别名在 PostgreSQL 中进行操作时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18461965/

相关文章:

sql - 如何在 RPostgreSQL 中使用参数(插入数据)

c# - 返回查询中的最大值

sql - Pentaho 与 PostgreSQL 的连接

sql - SQL Server 中是否需要主键?

sql - postgres 返回的结果不正确

python - Psycopg2 不喜欢以小写字母开头的表名

sql - 修改 SQL 语句以追加表中的列

python - Flask-Migrate 未检测到表格

php - 如何使用 php 和 mysql 使用多对多关系提取数据

mysql - 获取每个 friend 的所有最后一条消息 - SQL