我在查询时遇到问题。我想对我的薪资系统进行操作。我这是我的查询,它不起作用。
查询:
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 - 请注意 shiftinminutes
和 shiftinhours
是如何只计算一次而不是两次的。可读性很重要,不要重复计算,以后很难维护。
顺便说一句,看看interval data type in PostgreSQL , 你可以从中提取小时和分钟
关于sql - 使用列别名在 PostgreSQL 中进行操作时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18461965/