postgresql 如何在WHERE中使用UNION添加的虚拟列名?

yi0zb3m4  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(2)|浏览(114)
SELECT '1000000' AS number
UNION ALL
SELECT '541' AS number
UNION ALL
SELECT '-500' AS number
UNION ALL
SELECT '100' AS number
UNION ALL
SELECT number, 'biggest' AS result
WHERE number = 1000000

我的任务是从我添加的那些数字中找到最大的数字。

SELECT '1000000' AS number
UNION ALL
SELECT '541' AS number
UNION ALL
SELECT '-500' AS number
UNION ALL
SELECT '100' AS number
UNION ALL
SELECT number, 'biggest' AS result
WHERE number = 1000000

我的任务是从我添加的那些数字中找到最大的数字。

2lpgd968

2lpgd9681#

您需要将查询 Package 在派生表中,以便能够访问列别名

select *
from (
  SELECT 1000000 AS number
  UNION ALL
  SELECT 541 AS number
  UNION ALL
  SELECT -500 AS number
  UNION ALL
  SELECT 100 AS number
)
WHERE number = 1000000

但是要找到最大的数字,可以使用order bylimit

select *
from (
  SELECT 1000000 AS number
  UNION ALL
  SELECT 541 AS number
  UNION ALL
  SELECT -500 AS number
  UNION ALL
  SELECT 100 AS number
)
order by number desc 
limit 1

或者,您也可以使用VALUES子句来简化此操作:

select *
from (
  values (1000000),(541),(-500),(100)
) as t(number)
order by number desc 
limit 1
0md85ypi

0md85ypi2#

您可以将公共表表达式与FETCH一起使用,如下所示:

WITH CTE_Number AS (
SELECT 1000000 AS number
UNION ALL
SELECT 541 AS number
UNION ALL
SELECT -500 AS number
UNION ALL
SELECT 100 AS number
    )
SELECT Number,'Biggest' as result
FROM CTE_Number
ORDER BY Number DESC
FETCH FIRST ROW ONLY;

相关问题