SQL how to do 1 hour interval

只愿长相守 提交于 2019-12-11 08:38:04

问题


I have sql query which returns record by date specified What I want to do is group them by 1 hour interval My query returns a date and interval. interval value looks like this 8:00,8:30,9:00,9:30,10:00 as you can see the interval has produce 5 value what I want to do is group them by this 8:00-9:00,9:00-10:00

I have designed a query:

SELECT DATEPART(HOUR,VC.DATE+ VC.INTERVAL) AS DATE
      ,DATEPART(HOUR,VC.INTERVAL) AS INTERVAL 
      FROM VMUK_Q1R_IB_CONSOLIDATED VC

But the problem with this it display like this 8,8,9,9,10 How to I achieve this?


回答1:


What you need is to create a set of hourly values and join back to it based on the hour part of your value. This will make sure the missing 'buckets' are represented. The following CTE will give you the lookup for 24 hours - you could do the same thing with a static lookup table too.

with ranges 
as 
(
select 0 as value
union all 
select r.value+ 1 from ranges r where r.value <= 24
)
select 
r.value start
from ranges r



回答2:


You could fix this by a calculation or formatting. I think formatting would be simpler for this example. Try this:

SELECT Convert(VarChar(20), DATEPART(HOUR,VC.INTERVAL)) + ':00' AS DATE
     ,DATEPART(HOUR,VC.INTERVAL) AS INTERVAL 
FROM VMUK_Q1R_IB_CONSOLIDATED VC

If you want the full date + time shown, rounded down, try this:

SELECT Convert(VarChar(20), VC.Date, 101) + Convert(VarChar(20), DATEPART(HOUR,VC.INTERVAL)) + ':00' AS DATE
     ,DATEPART(HOUR,VC.INTERVAL) AS INTERVAL 
FROM VMUK_Q1R_IB_CONSOLIDATED VC

If you want time ranges too, try this:

SELECT Convert(VarChar(20), VC.Date, 101) + Convert(VarChar(20), DATEPART(HOUR,VC.INTERVAL)) + ':00' AS DATE,
     ,DatePart(HOUR,VC.INTERVAL)) + ':00 - ' + DatePart(HOUR, DateAdd(HOUR, VC.INTERVAL, 1)) + ':00' AS TimeRange
     ,DATEPART(HOUR,VC.INTERVAL) AS INTERVAL 
FROM VMUK_Q1R_IB_CONSOLIDATED VC



回答3:


SELECT
    DATEPART(HOUR,VC.DATE+ VC.INTERVAL) AS DATE,
    case DATEPART(HOUR,VC.INTERVAL)
        when 0 then '00:00-00:59'
        when 1 then '01:00-01:59'
        .
        .
        etc.
        .
        .
        when 22 then '22:00-22:59'
        when 23 then '23:00-23:59'
    end AS INTERVAL 
FROM VMUK_Q1R_IB_CONSOLIDATED VC


来源:https://stackoverflow.com/questions/19837984/sql-how-to-do-1-hour-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!