带拆分的T-SQL分组

时间:2018-09-30 21:03:22

标签: sql sql-server tsql

我想对连续的类似值进行分组。我想将前3个Reg单元,一个ICU和最后3个Reg单元归为一组。问题是第三组与第一组相同,我无法将它们分别分组。我尝试了窗口函数和其他东西都没有用。将不胜感激任何想法。谢谢。

数据集

ID  OccpdID   Unit
1     1       Reg
1     2       Reg
1     3       Reg
1     4       ICU
1     5       Reg
1     6       Reg
1     7       Reg

结果为:

ID  OccpdID Unit    Group
1     1     Reg      1
1     2     Reg      1
1     3     Reg      1
1     4     ICU      2
1     5     Reg      3
1     6     Reg      3
1     7     Reg      3 

3 个答案:

答案 0 :(得分:3)

我不确定您希望ID如何/是否将其作为因素,但类似的方法会提供所需的结果:

SELECT
    ID
    , OccpdID
    , Unit
    , SUM(CASE WHEN Unit <> L OR L IS NULL THEN 1 ELSE 0 END) OVER (ORDER BY OccpdID) [Group]
FROM
    (
        SELECT
            ID
            , OccpdID
            , Unit
            , LAG(Unit, 1, NULL) OVER (ORDER BY OccpdID) L
        FROM YourTable
    ) Q

答案 1 :(得分:3)

我将使用lag()和一个累加的总和:

select t.*,
       sum(case when prev_unit = unit then 0 else 1 end) over (order by occpdid) as grp
from (select t.*, lag(t.unit) over (order by t.occpdid) as prev_unit
      from t
     ) t;

答案 2 :(得分:1)

您可以尝试在具有LAGSUM窗口函数的子查询中使用CASE WHEN

SELECT ID,OccpdID,Unit,SUM(CASE WHEN Unit <> prevVal THEN 1 ELSE 0 END) OVER(ORDER BY OccpdID) +1 as 'Group'
FROM (
    SELECT *, LAG(Unit) OVER(ORDER BY OccpdID) prevVal
    FROM Dataset
) t1

sqlfiddle