我的数据集如下:表示运输的移动,T
表示正在移动,F
表示Stationary
我希望对数据进行如下分类以进一步分析。需要基于列Class
导出Moving
,并且应从0
开始计数,并且当移动值从T
变为F
时,应从F
中的0
。下一列ID
是将移动集值从0
到增量级别进行分组。
输出:
答案 0 :(得分:0)
您可以使用通用表表达式来实现您的目标:https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql
首先,您必须按移动日期排序数据,然后可以使用ROW_NUMBER:https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql
这里有一个示例请求:
;WITH orderedMovements AS
(
SELECT [Date], [Moving], ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY [Date] ASC) AS [RowNum]
FROM [dbo].[movements]
), completedMovements AS
(
SELECT omo.[Date], omo.[Moving], 0 AS [Class], 0 AS [Id], omo.[RowNum] AS [RowNumBis]
FROM orderedMovements omo
WHERE [RowNum] = 1
UNION ALL
SELECT omo.[Date], omo.[Moving], IIF(cmo.[Moving] = omo.[Moving], cmo.[Class] + 1, 0) AS [Class], IIF(cmo.[Moving] = omo.[Moving], cmo.[Id], cmo.[Id] + 1) AS [Id], omo.[RowNum]
FROM orderedMovements omo
JOIN completedMovements cmo ON omo.[RowNum] = cmo.[RowNumBis] + 1
)
SELECT [Date], [Moving], [Class], [Id]
FROM completedMovements
OPTION (MAXRECURSION 100);