您好,我需要按特定时间段对数据进行分组的最佳解决方案。我需要将月份数据从 07:00:00 到 18:59:59 分组,然后从 19:00:00 到第二天 06:59:59。在数据库中有大量数据,因此首选快速有效的解决方案。
在查询中插入 Shift 字母也很好。有 4 个班次:A、B、C、D,我有日历表。
Table [Shiftcalendar]:
[ShiftDate] | [SHIFT] | [Nextshift]
2013-11-11 | N | A=B
2013-11-11 | D | C=A
2013-11-10 | N | D=C
.... | .... | ....
[Shift] 列代表白天或夜晚,[Nextshift] 列代表班次和下一班次。N 表示夜间,从 19:00:00 到次日 06:59:59,D 表示白天,从 07:00:00 到 18:59:59。
Table [wrkSpeedInfo]:
[wrkActionDate] | [wrkSpeed] | [wrkGlueValue] | [x1]
2013-11-11 07:00:35 | 200 | 300 | 20
2013-11-11 07:00:55 | 97 | 255 | 13
2013-11-11 07:01:23 | 127 | 124 | 15
.... | .... | .... | ....
我需要对 [wrkSpeed]、[wrkGlueValue] 和 [x1] 求和。
有人的帮助将不胜感激:)
PS.:别介意我的英语写作能力,我还在提高它的边缘。
编辑:这么长时间以来,我做了很多查询来获取特定的日期和班次数据,但希望在一个查询中包含所有数据。
WHERE [wrkActionDate] BETWEEN '2013-10-03 07:00:00' AND '2013-10-03 18:59:59'
我可以发布完整的查询,但它需要很多空间,什么时候需要解释更多我想要做的事情。
编辑:好的,有人说要发布完整的查询:
SELECT [wrkActionDate]
,[wrkCntrId]
,DATEDIFF(second, (SELECT TOP 1 t2.[wrkActionDate] FROM [DW].[dbo].[wrkSpeedInfo] as t2 WHERE [wrkCntrId] = 'S1' AND t2.[wrkActionDate] < t1.[wrkActionDate] ORDER BY t2.[wrkActionDate] DESC), [wrkActionDate])/60.0 AS MinPassed
,SUM([wrkSpeed])*DATEDIFF(second, (SELECT TOP 1 t2.[wrkActionDate] FROM [DW].[dbo].[wrkSpeedInfo] as t2 WHERE [wrkCntrId] = 'S1' AND t2.[wrkActionDate] < t1.[wrkActionDate] ORDER BY t2.[wrkActionDate] DESC), [wrkActionDate])/60.0 AS SumWrkSpeed
,SUM([wrkGlueValue])*DATEDIFF(second, (SELECT TOP 1 t2.[wrkActionDate] FROM [DW].[dbo].[wrkSpeedInfo] as t2 WHERE [wrkCntrId] = 'S1' AND t2.[wrkActionDate] < t1.[wrkActionDate] ORDER BY t2.[wrkActionDate] DESC), [wrkActionDate])/60.0 AS SumWrkGlueValue
,SUM([x1]) AS SumX1
FROM [DW].[dbo].[wrkSpeedInfo] as t1
WHERE [wrkActionDate] BETWEEN '2013-10-03 07:00:00' AND '2013-10-03 18:59:59' AND [wrkCntrId] = 'S1'
GROUP BY [wrkCntrId], [wrkActionDate]
因此,如果我可以在一个查询中获取所有月份的数据,那就太好了,因为现在只获取一个班次的数据。
得到类似的东西会很棒:
[ShiftDate] | [SHIFT] | [Nextshift] | SUM([wrkSpeed]) | SUM([wrkGlueValue]) | SUM([x1])
编辑:他们使用 MS SQL 2012。不能改变结构或任何东西,只能从数据库中选择数据。