我想做这个:
SELECT (EXTRACT(epoch FROM (
case when
(select date from history where statut='X' and id=6 order by date desc limit 1)
is null then now()
else
(select date from history where statut='X' and id=6 order by date desc limit 1) end)
- case when
(select date from history where statut in ('Y', 'U') and id=6 order by date desc limit 1)
is null then now()
else
(select date from history where statut in ('Y', 'U') and id=6 order by date desc limit 1)
end
)/3600)
此请求在历史记录中搜索某些法规的修改日期,减去它,并以小时为单位返回差异。如果没有找到任何行,则应将其替换为0。
它有效,但我们都可以看到它是多么丑陋。
有没有办法美化我的查询?
一个简化:
case when X is null
then Y
else X
end
可以写成:
coalesce(X, Y)
这会将您的查询减少到:
SELECT (
EXTRACT(epoch FROM
coalesce((select date from history where statut='X' and id=6 order by date desc limit 1), now())
-
coalesce((select date from history where statut in ('Y', 'U') and id=6 order by date desc limit 1), now())
) / 3600
)
另一个简化:
select X from T order by X desc limit 1
只是:
select max(X) from T
产量:
SELECT (
EXTRACT(epoch FROM
coalesce((select max(date) from history where statut='X' and id=6), now())
-
coalesce((select max(date) from history where statut in ('Y', 'U') and id=6), now())
) / 3600
)