0

我正在尝试正确编写 TSQL 以创建一个包含以下旧列和新派生列的新表:

日期、10 分钟时间、代码、价格、SumItems。

新表应包括两个派生列;10minTime 仅包含 10min 时间段(例如 10:40、10:30、10:20),SumItems 包含每 10min 时间段内的项目总和。其他列应保持不变。

原始数据是这样的:

    Date        Time       Code Price   Items
    2012-05-10  10:43:00    a   1351.9  2
    2012-05-10  10:42:00    a   1351.7  5
    2012-05-10  10:41:00    a   1351.3  5
    2012-05-10  10:40:00    a   1351.5  8
    2012-05-10  10:39:00    a   1351.8  3
    2012-05-10  10:38:00    a   1351.9  5
    2012-05-10  10:37:00    a   1351.5  6
    2012-05-10  10:35:00    a   1352.2  2
    2012-05-10  10:34:00    a   1352.0  3
    2012-05-10  10:32:00    a   1352.3  6

这是我到目前为止所拥有的,但它有错误。如果我删除 [Price] 然后它运行但产生错误的结果。

SELECT TOP 1000 [date]
      ,min([time]) as 10minTime
      ,[price]
      ,sum([Items]) as SumItems
  FROM [MarketData].[dbo].[MyData]
  group by [Date],DATEPART(hour, [Time]),(DATEPART(minute, [Time]))%10
  order by [date] desc, 10minTime desc

感谢您的任何建议/帮助!

4

1 回答 1

1
SELECT TOP 1000 
     m1.date
      ,min(m1.time) as 10minTime
      ,(Select price from dbo.MyData m2
        where m2.Date = m1.Date
        and DATEPART(hour, m2.Time) = DATEPART(hours, m1.Time)
        and DATEPART(minute, m2.Time) = DATEPART(minute, m2.Time) %10)

      ,sum(Items) as SumItems
  FROM dbo.MyData m1
  group by [Date],DATEPART(hour, [Time]),(DATEPART(minute, Time))%10
  order by [date] desc, 10minTime desc
于 2012-06-29T16:54:49.117 回答