Sql server 使用SQL Server添加行以生成摘要
给定以下有序数据集(间隔1分钟),我将如何使用Microsoft SQL Server创建一个新的记录集,该记录集将给定项的所有单个代码相加,并显示如下所示的摘要?我想我应该能够在分区上使用某种聚合函数,但我不知道从哪里开始 请注意,Sql server 使用SQL Server添加行以生成摘要,sql-server,Sql Server,给定以下有序数据集(间隔1分钟),我将如何使用Microsoft SQL Server创建一个新的记录集,该记录集将给定项的所有单个代码相加,并显示如下所示的摘要?我想我应该能够在分区上使用某种聚合函数,但我不知道从哪里开始 请注意,DateTime为DateTime,其余列为varchar类型。我正在使用SQL Server 2012 Express 输入数据: DateTime Item Code Description 2016-12-02 1
DateTime
为DateTime
,其余列为varchar
类型。我正在使用SQL Server 2012 Express
输入数据:
DateTime Item Code Description
2016-12-02 16:34:00 0 1 Some Description
2016-12-02 16:35:00 0 1 Some Description
2016-12-02 16:36:00 0 1 Some Description
2016-12-02 16:37:00 0 1 Some Description
2016-12-02 16:38:00 0 1 Some Description
2016-12-02 16:39:00 0 1 Some Description
2016-12-02 16:40:00 0 2 Some Description
2016-12-02 16:41:00 0 2 Some Description
2016-12-02 16:42:00 0 2 Some Description
2016-12-02 16:43:00 0 4 Some Description
2016-12-02 16:44:00 0 4 Some Description
2016-12-02 16:45:00 0 4 Some Description
2016-12-02 16:46:00 0 4 Some Description
2016-12-02 16:47:00 0 4 Some Description
2016-12-02 16:48:00 1 1 Some Description
2016-12-02 16:49:00 1 2 Some Description
2016-12-02 16:50:00 1 2 Some Description
2016-12-02 16:51:00 1 2 Some Description
2016-12-02 16:52:00 1 2 Some Description
2016-12-02 16:53:00 1 3 Some Description
2016-12-02 16:54:00 0 1 Some Description
2016-12-02 16:55:00 0 1 Some Description
2016-12-02 16:56:00 0 1 Some Description
2016-12-02 16:57:00 0 8 Some Description
2016-12-02 16:58:00 0 8 Some Description
2016-12-02 16:59:00 0 8 Some Description
2016-12-02 17:00:00 0 6 Some Description
2016-12-02 17:01:00 0 6 Some Description
预期输出数据(开始日期应为代码第一次出现的日期时间,结束日期应为代码最后一次出现的日期时间):
您想要的是将连续日期的孤岛分组。是Jeff Moden撰写的一篇文章,提供了此问题的解决方案:
WITH Cte AS(
SELECT *,
rn = DATEADD(MINUTE, - ROW_NUMBER() OVER(PARTITION BY Item, Code ORDER BY DateTime), Datetime)
FROM Data
)
SELECT
StartDate = MIN(DateTime),
EndDate = MAX(DateTime),
Item,
Code,
Description = MAX(Description)
FROM Cte
GROUP BY
Item, Code, rn
ORDER BY
StartDate, EndDate;
您想要的是对连续日期的孤岛进行分组。是Jeff Moden撰写的一篇文章,提供了此问题的解决方案:
WITH Cte AS(
SELECT *,
rn = DATEADD(MINUTE, - ROW_NUMBER() OVER(PARTITION BY Item, Code ORDER BY DateTime), Datetime)
FROM Data
)
SELECT
StartDate = MIN(DateTime),
EndDate = MAX(DateTime),
Item,
Code,
Description = MAX(Description)
FROM Cte
GROUP BY
Item, Code, rn
ORDER BY
StartDate, EndDate;
如果您能在样本数据中提供一些真实日期,那就太好了。应该包括Felix,我来帮助测试等。我现在已经包括了日期时间。如果您能在样本数据中提供一些真实日期,那就太好了。Felix,我应该包括协助测试等。我现在已经包括了日期时间。感谢Felix的输入,我会查出来的!谢谢Felix的输入,我会查出来的!