选择具有最大值的列名 -- 将 PostgreSQL 查询转换为 Oracle?

问题描述 投票:0回答:1

表名:

employment_by_industry

enter image description here

对于每一行,我想选择具有最大值的列名称:

enter image description here


我正在寻找在 Oracle 中执行此操作的简洁方法,列名仅在 SQL 查询中列出一次。

这里有一个 PostgreSQL 技术:

select objectid, (SELECT industry FROM (values 
       (agr_forest_fish, 'agr_forest_fish'),
       (mining_quarry, 'mining_quarry'),
       (mfg, 'mfg'),
       (electric, 'electric'),
       (water_sew, 'water_sew')
  ) as t(emp, industry)
  order by emp DESC
  LIMIT 1)
from employment_by_industry

来源

https://dbfiddle.uk/ZdJhvNZC

从技术上讲,我认为列名称被列出多次。但也许已经足够接近了。

PostgreSQL 查询可以适应在 Oracle 中工作吗? (任何版本)

sql oracle select
1个回答
0
投票

在 Oracle 上,假设每一行始终只有一个最大就业值,我们可以在这里使用

GREATEST()
技巧:

WITH cte AS (
    SELECT t.*,
        GREATEST(agr_forest_fish, mining_quarry, mfg, electric, water_sew) AS max_val
    FROM employment_by_industry t
)

SELECT
    objectid,
    CASE WHEN agr_forest_fish = max_val THEN 'agr_forest_fish'
         WHEN mining_quarry = max_val THEN 'mining_quarry'
         WHEN mfg = max_val THEN 'mfg'
         WHEN electric = max_val THEN electric
         WHEN water_sew = max_val THEN 'water_sew' END AS industry
FROM cte
ORDER BY objectid;
© www.soinside.com 2019 - 2024. All rights reserved.