如何获得连续时间的最小/最大时间和此范围内的次数?

时间:2018-01-18 07:06:22

标签: sql sql-server

日期:

2015-04-01 12:00
2015-04-01 11:00
2015-04-01 10:
2015-04-01 09:
2015-04-01 08:00 // <---
2015-04-01 05:00
2015-04-01 04:00
2015-04-01 03:00
2015-04-01 02:00
2015-04-01 01:00 // <---
2015-03-31 22:00
2015-03-31 21:00
2015-03-31 20:00
2015-03-31 19:00 // <---

我想得到这个结果:

MaxTime          | MinTime          | Count
2015-04-01 12:00 | 2015-04-01 08:00 | 5
2015-04-01 05:00 | 2015-04-01 01:00 | 5
2015-03-31 22:00 | 2015-03-31 19:00 | 4

2 个答案:

答案 0 :(得分:1)

尝试此查询

select
    max(dateColumn), min(dateColumn), count(dateColumn)
from (
    select 
        dateColumn, datepart(dayofyear, dateColumn)*24 + datepart(hh, dateColumn) - row_number() over (order by dateColumn) grp
    from
        MyTable
) t
group by grp

答案 1 :(得分:0)

样本数据

IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp

;With cte(Dates)
AS
(
SELECT '2015-04-01 12:00' UNION ALL
SELECT '2015-04-01 11:00' UNION ALL
SELECT '2015-04-01 10:00' UNION ALL
SELECT '2015-04-01 09:00' UNION ALL
SELECT '2015-04-01 08:00' UNION ALL
SELECT '2015-04-01 05:00' UNION ALL
SELECT '2015-04-01 04:00' UNION ALL
SELECT '2015-04-01 03:00' UNION ALL
SELECT '2015-04-01 02:00' UNION ALL
SELECT '2015-04-01 01:00' UNION ALL
SELECT '2015-03-31 22:00' UNION ALL
SELECT '2015-03-31 21:00' UNION ALL
SELECT '2015-03-31 20:00' UNION ALL
SELECT '2015-03-31 19:00' 
)
SELECT * INTO #Temp FROM cte     
SELECT * FROM   #Temp

使用Row_number()Over()函数

的预期结果脚本
SELECT DISTINCT
        MAX(Dates)OVER(PArtition by BatchSeq Order by (SELECT 1)) AS MaxTime
       ,MIN(Dates)OVER(PArtition by BatchSeq Order by (SELECT 1)) AS MinTime
       ,COUNT(Dates)OVER(PArtition by BatchSeq Order by (SELECT 1)) As [Count]
FROM
(
SELECT Dates  ,  ((ROW_NUMBER()OVER(ORDER BY (SELECT 1))-1)/5+1) AS BatchSeq  FROM
#Temp
)dt
ORDER BY 1 DESC

使用分组依据()函数

的预期结果脚本
SELECT 
        MAX(Dates)   AS MaxTime
       ,MIN(Dates)  AS MinTime
       ,COUNT(Dates) As [Count]
FROM
(
SELECT Dates ,((ROW_NUMBER()OVER(ORDER BY (SELECT 1))-1)/5+1) AS BatchSeq  FROM
#Temp
)dt
GROUP BY BatchSeq
ORDER BY 1 DESC

结果

 MaxTime                MinTime         Count
  --------------------------------------------
  2015-04-01 12:00  2015-04-01 08:00    5
  2015-04-01 05:00  2015-04-01 01:00    5
  2015-03-31 22:00  2015-03-31 19:00    4