sql如何将时间序列数据转换为临时数据

时间:2014-08-18 09:07:38

标签: sql sql-server

我有一个这种格式的SQL表 -

Company Size segment        DATE    
ABC     Large cap           01-Mar-98    
ABC     Large cap           01-Sep-98    
ABC     Mid cap             01-Mar-99    
ABC     Mid cap             01-Sep-99    
ABC     Large cap           01-Mar-00    

我想转换为此格式 - 结束日期是每个期间的最后日期。例如,第一个“大型上限”期间的开始日期为01-Mar-98,该期间的结束日期为28-feb-99

Security    Size segment   Start date   End date       
ABC        Large Cap       01-Mar-98    28-feb-99    
ABC        Mid Cap         1-mar-99     28-feb-00    
ABC        Large Cap       1-mar-00     NULL    

我如何在sql server中执行此操作?

谢谢。

2 个答案:

答案 0 :(得分:0)

SELECT Company, [Size segment], Min(DATE) [Start date], MAX(DATE) [End date]
FROM TableName 
GROUP BY Company, [Size segment]

答案 1 :(得分:0)

尝试这个:

CREATE TABLE B
(ID INT IDENTITY PRIMARY KEY, [Company] varchar(3), [Size segment] varchar(9), [DATE] datetime)
;

INSERT INTO B
([Company], [Size segment], [DATE])
VALUES
('ABC', 'Large cap', '1998-03-01 00:00:00'),
('ABC', 'Large cap', '1998-09-01 00:00:00'),
('ABC', 'Mid cap', '1999-03-01 00:00:00'),
('ABC', 'Mid cap', '1999-09-01 00:00:00'),
('ABC', 'Large cap', '2000-03-01 00:00:00')
;

;WITH tmp AS (
SELECT id, company, [Size segment], [date], row_number() over(order by DATE) row_index
FROM B
)
select b.*, DATEADD(dd, -1, t2.[date])
from B 
left join tmp t1 ON t1.id = b.id
left join tmp t2 ON t1.row_index + 1 = t2.row_index
WHERE t1.[size segment] <> t2.[size segment]
UNION
select TOP 1 *, NULL
from B
ORDER BY [date] DESC