具有已停止期间的组岛查询

时间:2017-02-28 15:39:43

标签: sql sql-server

我有一张表如下,

create table #ph (symbol char(2), FisrtDate date, LastDate, value1 int, value2 int, value3 int)
insert into #ph select AA, '20120101', '20130201',  1, 1000, 200
insert into #ph select AA, '20130202', '20150101',  2, 300,  500
insert into #ph select AA, '20150102', '20170101',  2, 300 , 500
insert into #ph select AB, '20120104', '20150101',  1, 200, 500
insert into #ph select AB, '20150104', '20170101',  1, 200, 500
insert into #ph select AB, '20170106', '20170201',  1, 300, 500

我希望输出像,

Symbol | date_from| date_to  | value1 | value2 | value3
  AA   | 20120101 | 20130201 | 1      | 1000   | 200
  AA   | 20130202 | 20170101 | 1      | 300    | 500
  AB   | 20120104 | 20170101 | 1      | 200    | 500
  AB   | 20120106 | 20170201 | 1      | 300    | 500

我正在寻找群岛问题,但我很困惑。

2 个答案:

答案 0 :(得分:4)

查看您的数据,如果我理解正确,您想要显示MIN,那么没有更改value1,value2和value3的行的MAX日期?

如果是这样,那么简单的GROUP BY应该这样做:

SELECT symbol, MIN(FirstDate), MAX(LastDate), value1, value2, value3
  FROM #ph
 GROUP BY symbol, value1, value2, value3

答案 1 :(得分:-1)

最小和最大聚合函数将根据要求使用。然后,这些聚合函数将构成我们在查询中进行分组的基础。

SELECT symbol, MIN(FirstDate) as [date_from], MAX(LastDate) as [date_to], value1, value2, value3
FROM #ph
GROUP BY symbol, value1, value2, value3