选择具有最大值的列名(在SQL查询中只列出一次列名)

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

输入:

enter image description here

https://dbfiddle.uk/vPuEVN2v

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

enter image description here


在 SQLite 中最简洁的方法是什么,其中列名仅在 SQL 查询中列出一次?

例如,在 Oracle 中是这样实现的:

select objectid, max(col_name) keep (dense_rank first order by col_val desc) max_col_name
from employment_by_industry
unpivot (
  col_val
  for col_name in (
    agr_forest_fish, mining_quarry, mfg, electric, water_sew  --cols only listed once
  )
)
group by objected
sql sqlite select
1个回答
0
投票

您可以使用

union all
取消旋转表格,并使用
row_number
在组内订购

select objectid, col_name
from (
  select objectid, row_number() over(partition by objectid order by col_val desc) rn, col_name
  from (
    select objectid, 'agr_forest_fish' col_name, agr_forest_fish col_val 
    from employment_by_industry

    union all

    select objectid, 'mining_quarry' col_name, mining_quarry
    from employment_by_industry
    ...
    ) t
)
where rn=1
© www.soinside.com 2019 - 2024. All rights reserved.