SQL查询以隔离数据

时间:2019-07-23 06:28:23

标签: sql-server spotfire

我的数据集如下:表示运输的移动,T表示正在移动,F表示Stationary

我希望对数据进行如下分类以进一步分析。需要基于列Class导出Moving,并且应从0开始计数,并且当移动值从T变为F时,应从F中的0。下一列ID是将移动集值从0到增量级别进行分组。

输出:

Img

1 个答案:

答案 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);