SQL按顺序计算1的数量

时间:2018-03-26 06:55:29

标签: sql sql-server tsql sql-server-2012 gaps-and-islands

我有下表,你可以看到ID不一样。所以我不能分组。我需要计算所有顺序的。喜欢从id 9到13,从id 20到23.我怎么做?

enter image description here

1 个答案:

答案 0 :(得分:1)

以下是LAGLEAD的解决方案。

;WITH StackValues AS
(
    SELECT
        T.*,
        PreviousStatus = LAG(T.Status, 1, 0) OVER (ORDER BY T.ID ASC),
        NextStatus = LEAD(T.Status, 1, 0) OVER (ORDER BY T.ID ASC)
    FROM
        #YourTable AS T
),
ValuesToSum AS
(
    SELECT
        L.*,
        ValueToSum = CASE 
            WHEN L.Status = 1 AND L.PreviousStatus = 1 AND L.NextStatus = 0 THEN 1
            ELSE 0 END
    FROM
        StackValues AS L
)
SELECT
    Total = SUM(V.ValueToSum)
FROM
    ValuesToSum AS V

LAG将为您提供N上一行(此示例为N = 1),而LEAD将为您提供N下一行({{1}这个例子)。该查询根据前一个和下一个值生成另一列(N = 1),并使用它的结果进行求和。