GROUP BY Specific Column并在SQL中将一列连续值相加

时间:2018-04-12 07:02:39

标签: sql sql-server

我使用此查询有一个数据集:

SELECT ThanaId, RoadId, (ToChain-FromChain) as TotalChain, FromChain, ToChain, SurfaceType
FROM Segment
WHERE ThanaId = (SELECT MIN(ThanaId) AS ThanaId FROM RdLineDiagTemp)
   AND RoadId = (SELECT MIN(RoadId) AS RoadId FROM RdLineDiagTemp)
ORDER BY FromChain

数据集是:

 ThanaId | RoadId | TotalChain | FromChain | ToChain | SurfaceType
 54701   |1368    |3100        |0          |3100     |BC
 54701   |1368    |2000        |3100       |5100     |BC
 54701   |1368    |750         |5100       |5850     |BC
 54701   |1368    |920         |5850       |6770     |BC
 54701   |1368    |73          |6770       |6843     |BC
 54701   |1368    |2000        |6843       |8843     |BC
 54701   |1368    |4007        |8843       |12850    |Ert
 54701   |1368    |2000        |12850      |14850    |BC

我想这样表现出来:

 ThanaId | RoadId | TotalChain | FromChain | ToChain | SurfaceType
 54701   |1368    |8843        |0          |8843     |BC
 54701   |1368    |4007        |8843       |12850    |Ert
 54701   |1368    |2000        |12850      |14850    |BC

这里,每个连续的TotalChain对连续的相同表面类型求和。我应该写什么查询来实现这个目标?

2 个答案:

答案 0 :(得分:2)

这是一个空白和岛屿问题。

您可以使用如下查询:

SELECT ThanaId, 
   RoadId, 
   SUM(TotalChain) AS TotalChain, 
   MIN(FromChain) AS FromChain, 
   MAX(ToChain) AS ToChain, 
   SurfaceType
FROM 
(
   SELECT ThanaId, RoadId, (ToChain-FromChain) as TotalChain, 
          FromChain, ToChain, SurfaceType,
          ROW_NUMBER() OVER (PARTITION BY ThanaId, RoadId 
                             ORDER BY FromChain) -
          ROW_NUMBER() OVER (PARTITION BY ThanaId, RoadId, SurfaceType 
                             ORDER BY FromChain) AS grp
   FROM Segment
   WHERE ThanaId = (SELECT MIN(ThanaId) AS ThanaId FROM RdLineDiagTemp)
         AND 
         RoadId = (SELECT MIN(RoadId) AS RoadId FROM RdLineDiagTemp)
) AS t
GROUP BY ThanaId, RoadId, SurfaceType, grp
ORDER BY FromChain

Demo here

注意:我假设字段FromChain确定了行顺序。

答案 1 :(得分:0)

使用row_numbers的差异Giorgos Betsos表示这是间隙和岛屿问题。

select ThanaId, RoadId, max(ToChain) - min(FromChain) TotalChain, 
                        min(FromChain) FromChain, max(ToChain) ToChain, SurfaceType 
from (
    select *,
          row_number() over (order by ThanaId, RoadId) Seq1,
          row_number() over (partition by SurfaceType order by ThanaId, RoadId) Seq2 
    from table t
) tt
group by ThanaId, RoadId, SurfaceType, (Seq1-Seq2)