简体   繁体   English

Oracle SQL动态选择列名

[英]Oracle SQL dynamically select column name

A user gave me a table that looks like the following. 用户给了我一张看起来像下面的表格。

Name   HH08   HH09   HH10   HH11   HH12   HH13
Bob      2      3      4      2      7      1
Steve    2      9      3      2      2      5
Mike     2      2      2      2      3      2
Pat      1      0      2      0      0      0

I need some sql that will select the row based on the name, and the column based on the current hour of sysdate when the query is run. 我需要一些sql,它将根据名称选择行,并根据运行查询时的sysdate当前小时选择列。

If it is 9:27 am and the user is Steve, the sql needs to select the 9 value. 如果是上午9:27,并且用户是Steve,则sql需要选择9值。

Is there any simple sql that will do this, or do I need to restructure the table the user gives me, which will be occassionally. 是否有任何简单的sql可以做到这一点,或者我是否需要重新构造用户给我的表,这会偶尔发生。

Thanks in advance. 提前致谢。

Try: 尝试:

select case to_char(sysdate,'hh24')
           when '08' then hh08
           when '09' then hh09
           when '10' then hh10
           when '11' then hh11
           when '12' then hh12
           when '13' then hh13
       end OutputValue
from TableName
WHERE Name = 'Steve'
SELECT 'HH'+convert(char(2),DATEPART(hour,getdate()))
FROM TableName
WHERE Name = 'Steve'

try this out 试试这个

with t as (
  select 'Bob' name, 2 hh08, 3 hh09, 4 hh10, 2 hh11, 7 hh12, 1 hh13 from dual union all
  select 'Steve',    2,      9,      3,      2,      2,      5 from dual union all
  select 'Mike',     2,      2,      2,      2,      3,      2 from dual union all
  select 'Pat',      1,      0,      2,      0,      0,      0 from dual 
)
--/\-- Data sample --/\--
select value from t
  unpivot(value for hr in (hh08 as '08', hh09 as '09', hh10 as '10', hh11 as '11', hh12 as '12', hh13 as '13') )
 where hr = to_char(sysdate, 'HH24')
   and name = 'Pat';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM