假设你有一个表(我正在使用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和Date有数百万行) - 我想在价格改变时返回记录(寻找比使用游标更好的东西并迭代):
我试图找出如何获得:
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
即。另一种看待它的方式是,我正在寻找价格保持不变的一系列日期。
答案 0 :(得分: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)
答案 1 :(得分:2)
如果值没有改变,std偏差将为零
select secId
from ...
group by secId
having count(*) = 1
OR stdev(price) = 0
答案 2 :(得分: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