5

假设您有一个类似的表(我使用 SQL Server 2008,没有审核日志 - 表很大):

 SecID | Date    | Price
 1       1/1/11      10
 1       1/2/11      10
 1       1/3/11      5
 1       1/4/11      10
 1       1/5/11      10

假设这个表是巨大的(不同 secID 和日期的数百万行) - 我想在价格变化时返回记录(寻找比使用游标和迭代更好的东西):

我试图弄清楚如何获得:

 SecID | StartDate | EndDate | Price
 1        1/1/11      1/2/11    10
 1        1/3/11      1/3/11    5
 1        1/4/11      1/5/11    10

即另一种看待它的方式是,我正在寻找价格保持不变的一系列日期。

4

3 回答 3

8

这是一个“孤岛”问题。

declare @Yourtable table
 (SecID int, Date Date, Price int)

 INSERT INTO @Yourtable
SELECT 1,GETDATE()-5,10 union all
SELECT 1,GETDATE()-4,10 union all
SELECT 1,GETDATE()-3,5 union all
SELECT 1,GETDATE()-2,10 union all
SELECT 1,GETDATE()-1, 10

;WITH cte AS
(
SELECT SecID,Date,Price,
       ROW_NUMBER() OVER (PARTITION BY SecID ORDER BY Date) -
       ROW_NUMBER() OVER (PARTITION BY Price, SecID ORDER BY Date) AS Grp
FROM @Yourtable
)
SELECT SecID,Price, MIN(Date) StartDate, MAX(Date) EndDate
FROM cte
GROUP BY SecID, Grp, Price
ORDER BY SecID,  MIN(Date)
于 2011-01-19T18:06:22.447 回答
2

如果值不变,则标准偏差为零

select secId
  from ...
 group by secId
having count(*) = 1  
    OR stdev(price) = 0
于 2011-01-19T18:06:06.200 回答
0

我认为这应该有效

SELECT SecID, Min(Date) AS StartDate, Max(Date) AS EndDate, Price FROM BigTable GROUP BY SecID, EndDate Having Min(Date) != MAx(Date) And Date != NULL
于 2011-01-19T17:39:05.290 回答