2

我有一个包含三列的表:日期、时间和价格。“时间”列大约是分钟间隔,但不是每分钟间隔都表示。我希望创建一个包含 Date、FlooredTime、LastPriceInInterval 的新表,其中 FlooredTime = 每 10 分钟间隔开始时的时间,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;最大(日期部分(分钟,m1.时间)%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

谢谢!

后期编辑 - 我稍后会将结果用作合并表达式中的源表。

4

2 回答 2

2

您能否先确定区间,获取每个区间的最长时间,然后加入表格以获取价格?使用 aCTE您可以轻松实现此目的:

;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
于 2012-07-03T04:58:58.840 回答
1

Time您可以在各自的 10 分钟间隔内以相反的顺序对行进行排名,然后选择排名靠前的行:

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
;

这是查询的 SQL Fiddle 演示

于 2012-07-03T06:37:57.200 回答