SQL 查询以分离数据

SQL Query to segregate the data

我的数据集是这样的:其中表示transport的移动whereT表示是移动,F表示是Stationary

我想让数据分类如下,以便进一步分析。需要根据列 Moving 导出 Class 并且应该从 0 开始计算,当移动值从 T 变为 F 然后再次从F 来自 0。下一列 ID 是将移动集值从 0 分组到增量级别。

输出:

您可以使用通用 Table 表达式来实现您的目标: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);