1

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.

If it is 9:27 am and the user is Steve, the sql needs to select the 9 value.

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.

Thanks in advance.

2
  • Could always do it in a large case statement - not particularily nice but it would work Commented Jul 16, 2013 at 15:22
  • 3
    You should really re-structure the table, have it unique on name and hour rather than name alone. Commented Jul 16, 2013 at 15:24

3 Answers 3

5

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'
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT 'HH'+convert(char(2),DATEPART(hour,getdate()))
FROM TableName
WHERE Name = 'Steve'

try this out

1 Comment

This appears to be SQL Server syntax, not Oracle. DATEPART, getdate and convert aren't valid in Oracle. And even if you convert the syntax to use the equivalent Oracle constructs, the SELECT statement won't dynamically change the column name it is fetching, it would just select a string literal which happened to also be the name of the column.
1
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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.