选择每5行中的最大值

时间:2017-08-14 14:21:40

标签: sql-server tsql sql-server-2008-r2 greatest-n-per-group

我的总行数是可变的而不是固定的,所以有N行,我想将每5行作为一组分开,并在SQL中选择下表中的最大价格值。

Date     Price
20170101 100
20170102 110
20170103 90
20170105 80
20170109 76

20170110 50
20170111 55
20170113 80
20170115 100
20170120 99

20170121 88
20170122 98
20170123 120

因此,在前5组中,最高价格为110,第二组为100,最后一组最高价格为120.

3 个答案:

答案 0 :(得分:1)

您可以使用:

SELECT grp, MAX(Price) AS price
FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY DATE)  / 5 AS grp FROM tab) sub
GROUP BY grp;

-- OUTPUT
grp  price
0    110
1    100
2    120

<强> Rextester Demo

*假设日期是唯一的

修改

  

如:20170101 - 20170109 110

SELECT 
   CONVERT(VARCHAR(8),MIN(DATE),112) + '-' + CONVERT(VARCHAR(8),MAX(date),112)
     , MAX(Price) AS price
FROM (SELECT *, (ROW_NUMBER() OVER(ORDER BY DATE) ) / 5 AS grp FROM tab) sub
GROUP BY grp;

输出:

20170101-20170105   110
20170109-20170115   100
20170120-20170123   120

<强> Rextester Demo2

答案 1 :(得分:1)

使用公用表表达式对它们进行分组。

Data Frame

       "Date"    "Time"       "A"       "B"
0    2017-07-31  14:52:55  -0.032374  -0.027602   
1    2017-07-31  14:54:55  -0.032313  -0.027549   
2    2017-07-31  14:56:56  -0.032256  -0.027405   
3    2017-07-31  14:58:55  -0.032316  -0.027591   
4    2017-07-31  15:00:55  -0.032418  -0.027704   
5    2017-07-31  15:02:57  -0.032416  -0.027550   
6    2017-07-31  15:04:56  -0.032415  -0.027666
..          ...       ...        ...        ...
275  2017-08-01  00:00:56  -0.031791  -0.027092   
276  2017-08-01  00:02:56  -0.031779  -0.027155   
277  2017-08-01  00:04:56  -0.031901  -0.027234   
278  2017-08-01  00:06:55  -0.031903  -0.027206
..          ...       ...        ...        ... 
360  2017-01-08  02:50:55  -0.032319  -0.027562

输出

WITH CTE AS (SELECT RANK() OVER (ORDER BY Date) AS Rank, Price
             FROM yourtable)
SELECT (Rank - 1) / 5 AS GroupedDate, MAX(Price) AS MAXPRICE
FROM CTE
GROUP BY ((Rank - 1) / 5);

SQL小提琴:http://sqlfiddle.com/#!6/b5857/3/0

答案 2 :(得分:1)

您可以使用row_number,如下所示

;With cte as (
Select *, Bucket = Sum(RowN) over(Order by [date]) from (
    Select *, RowN = case when row_number()  over(order by [date]) % 5 = 0 then 1 else 0 end from #data1
) a
) Select top (1) with ties [Date], [Price]
from cte 
order by row_number() over (partition by Bucket order by Price desc)