您好,我需要按特定时间段对数据进行分组的最佳解决方案。我需要将月份数据从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
.... | .... | .... | ....
我需要SUM [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.无法更改结构或任何内容,只能从DB中选择数据。
答案 0 :(得分:1)
如果您想根据您必须的日期汇总所有值
GROUP BY CAST(wrkActionDate AS DATE)
但是您不希望精确地按日期分组,您希望根据您的班次模式进行分组。因此,您可以创建一个字段来计算特定时间内的哪个班次,然后根据该字段进行分组。
SELECT [Shift]
,SUM(wrkSpeed) AS wrkSpeed
,SUM(wrkGlueValue) AS wrkGlueValue
,SUM(x1) AS x1
FROM(
SELECT w.*,
CASE WHEN (DATEPART(HOUR, wrkActionDate) >= 7 AND DATEPART(HOUR, wrkActionDate) < 19)
THEN LEFT(CAST(wrkActionDate AS DATE),10)+' D'
ELSE LEFT(CAST(DATEADD(DAY, -1, wrkActionDate) AS DATE),10)+' N'
END AS [Shift]
FROM [DW].[dbo].wrkSpeedInfo w
) w
GROUP BY [Shift]