Connect with Expertise | Find Experts, Get Answers, Share Insights

Return result set for every hour of the day

Sl1ver's Avatar
C
 
Join Date: Mar 2009
Location: Cape Town, South Africa
Posts: 147
#1: Mar 5 '10
Hi im writing a sql query that needs to be grouped the hours in the day e.g
if its 10 am then it should have 10 different groups with data where the date and hour corresponds to that

i've tried
Expand|Select|Wrap|Line Numbers
  1. datepart(hour, getdate())
  2.  
but it does not return the required result, any help?

 
Join Date: Jan 2008
Location: Aberdeen, Scotland
Posts: 53
#2: Mar 5 '10

re: Return result set for every hour of the day


Hi,

I would suggest setting up a table with the hours in the day 1 - 24 (or am/pm) or something similar.
then creating a view from this as a left outer join to the table, the datepart(hour,getdate()) function can then be used to limit the number of records produced.

so something like this could work.

Expand|Select|Wrap|Line Numbers
  1. SELECT timename, eventname from
  2. (
  3. SELECT timename, eventname from tbltime LEFT OUTER JOIN tblevent on tbltime.timeid = Datepart(hour,tblevent.datetimefield)
  4. GROUP BY (tbltime.timename, Datepart(hour,tblevent.datetimefield))
  5. HAVING (Datepart(hour,tblevent.datetimefield) <= datepart(hour,getdate())
  6. )
  7.  
it needs something to refer against.

Hope this helps

Cheers

Leon
ck9663's Avatar
E
C
 
Join Date: Jun 2007
Posts: 2,206
#3: Mar 5 '10

re: Return result set for every hour of the day


Here's a sub-query. You can make this a view, a table variable, a derived table or a CTE and use it to join to your table.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. select colorder as hour_of_day
  4. from
  5.    (select colorder
  6.    from syscolumns c1 
  7.       inner join (select top 1 c2.id from syscolumns c2 group by c2.id having count(*) >= 24) c3 on c1.id = c3.id
  8.    where colorder <= 24) hours_in_day 
  9.  
  10.  
OR a UNION ALL

Expand|Select|Wrap|Line Numbers
  1. select * 
  2. from (
  3.    select 1 as hour_of_day
  4.    union all
  5.    select 2
  6.    union all
  7.    select 3
  8.    union all
  9.    select 4
  10.    union all
  11.    select 5
  12.    union all
  13.    select 6
  14.    union all
  15.    select 7
  16.    union all
  17.    select 8
  18.    union all
  19.    select 9
  20.    union all
  21.    select 10
  22.    union all
  23.    select 11
  24.    union all
  25.    select 12) hours_in_day
  26.  
Happy Coding!!!

~~ CK
Reply