如何从SQL Server中的同一个表获取最小日期和最小日期

时间:2016-08-19 06:25:56

标签: sql sql-server sql-server-2008

我有一张桌子

create table temp1
(
   GroupId int,
   DateCol Date,
   ValueCol int,
)
insert into temp1 values(1,'2016-1-1',10);
insert into temp1 values(1,'2017-1-1',20);
insert into temp1 values(1,'2018-1-1',30);
insert into temp1 values(2,'2016-5-1',101);
insert into temp1 values(2,'2017-5-1',102);
insert into temp1 values(2,'2018-5-1',103);

我希望获得按 GroupId列分组的日期范围(分钟到最小值):

ValueCol DateCol      DateColNextToMin
111      (min Date)   (next to Min Date)       


GroupId ValueCol DateCol      DateColNextToMin
1         10     2016-1-1         2017-1-1    
2         101    2016-5-1         2017-5-1                  

我该怎么做?

我试图获得彻底的 Windows功能 pivot 等,但似乎没有这样的优雅解决方案。

1 个答案:

答案 0 :(得分:2)

试试这个,

DECLARE @table Table
(
   GroupId int,
   DateCol Date,
   ValueCol int
)

INSERT INTO @table
VALUES
     (111,  '01-Aug-2016', 0)
    ,(111,  '02-Aug-2016', 0)
    ,(111,  '03-Aug-2016', 0)
    ,(111,  '04-Aug-2016', 0)
    ,(112,  '05-Aug-2016', 0)
    ,(112,  '06-Aug-2016', 0)
    ,(112,  '07-Aug-2016', 0)
    ,(112,  '08-Aug-2016', 0)

;WITH CTE AS 
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY DateCol ASC) AS RowNo 
    FROM  @table
)
SELECT c1.GroupId, c1.ValueCol, c1.DateCol, c2.DateCol
FROM CTE c1
INNER JOIN CTE c2 ON c1.GroupId = c2.GroupId 
    AND c1.RowNo = 1
    AND c2.RowNo = 2