我有一个包含三列的表:日期,时间和价格。 “时间”列大约是分钟间隔,但不是每分钟间隔都有代表。我希望创建一个包含Date,FlooredTime,LastPriceInInterval的新表,其中FlooredTime =每个10min间隔开始时的Time,LastPriceInInterval是每个时间间隔内最大可用时间的价格。
Old Table: New Table:
Date Time Price Date FlooredTime LastPriceInInterval
2012-05-10 02:50:00 1352.7 2012-05-10 02:40:00 1353.0
2012-05-10 02:46:00 1353.0 2012-05-10 02:30:00 1353.5
2012-05-10 02:45:00 1352.8
2012-05-10 02:44:00 1353.2
2012-05-10 02:43:00 1353.1
2012-05-10 02:42:00 1353.2
2012-05-10 02:40:00 1353.4
2012-05-10 02:39:00 1353.5
2012-05-10 02:38:00 1354.6
2012-05-11 03:31:00 1355.0
2012-05-11 03:29:00 1354.0
这是我到目前为止所拥有的,但现在我被卡住了。似乎内部select语句不喜欢在where子句中使用Max; MAX(日期部分(分,m1.Time)%10)。非常感谢知道如何使用允许的语法实现所需的结果。
SELECT TOP 1000 Date
,DATEADD(minute,-DATEPART(minute,Time)%10 ,Time) as FlooredTime
,(Select Price from dbo.MyData
where m3.Date = m1.Date
and DATEPART(hour, m3.Time) = DATEPART(hour, m1.Time)
and datepart(minute,m3.Time)/10 = Floor(datepart(minute,m1.Time)/10)
and datepart(minute,m3.Time)%10 = Max(datepart(minute,m1.Time)%10)
) as LastPriceInInterval
FROM dbo.MyData
where DATEPART(minute,Time)%10 = 0
order by Date Desc, Time Desc
谢谢!
延迟编辑 - 我稍后会将结果用作合并表达式中的源表。
答案 0 :(得分:2)
您是否可以先识别间隔,获取每个间隔的最长时间,然后加入表格以获取价格?使用CTE
您可以轻松实现此目的:
;WITH intervals(Date, T1, MaxTime) AS (
SELECT
Date
, DATEADD(minute, -DATEPART(minute, Time)%10, Time)
, MAX(Time) AS MaxTime
FROM dbo.MyData
GROUP BY Date
, DATEADD(minute, -DATEPART(minute, Time)%10, Time)
)
SELECT t.Date AS Date, i.T1 AS Time, t.Price
FROM dbo.MyData t
INNER JOIN intervals i ON t.Date = i.Date AND t.Time = i.MaxTime
ORDER BY Date DESC, Time DESC
答案 1 :(得分:1)
您可以在各自的10分钟间隔内以Time
的相反顺序对行进行排名,然后选择排名靠前的行:
WITH ranked AS (
SELECT
*,
FlooredTime = DATEADD(MINUTE, -DATEDIFF(MINUTE, 0, Time) % 10, Time),
TimeRank = ROW_NUMBER() OVER (
PARTITION BY DATEDIFF(MINUTE, 0, Time) / 10
ORDER BY Time DESC
)
FROM MyData
)
SELECT
Date,
FlooredTime,
LastPriceInInterval = Price
FROM ranked
WHERE TimeRank = 1
ORDER BY
Date DESC,
FlooredTime DESC
;