select语句中的SQL增量编号

时间:2014-07-16 17:14:08

标签: sql sql-server dynamic-sql

我遇到一个问题,我需要分组一组值,并在2列之间的差异大于或等于4时增加组号,请参阅下文。

更新:我添加了一个日期列,以便您可以查看订单,但我需要根据差异而不是日期来更新组。

+--------+-------+-------+----------+--------------+ | Date | Col 1 | Col 2 | Variance | Group Number | +--------+-------+-------+----------+--------------+ | 1-Jun | 2 | 1 | 1 | 1 | | 2-Jun | 1 | 1 | 0 | 1 | | 3-Jun | 3 | 2 | 1 | 1 | | 4-Jun | 4 | 1 | 3 | 1 | | 5-Jun | 5 | 1 | 4 | 2 | | 6-Jun | 1 | 1 | 0 | 2 | | 7-Jun | 23 | 12 | 11 | 3 | | 8-Jun | 12 | 11 | 1 | 3 | | 9-Jun | 2 | 1 | 1 | 3 | | 10-Jun | 13 | 4 | 9 | 4 | | 11-Jun | 2 | 1 | 1 | 4 | +--------+-------+-------+----------+--------------+

1 个答案:

答案 0 :(得分:2)

组号只是variance列中显示4个或更多的次数。您可以使用相关子查询来获取此信息:

select t.*,
       (select 1 + count(*)
        from table t2
        where t2.date < t.date and t2.variance >= 4
       ) as GroupNumber
from table t;

在SQL Server 2012+中,您还可以使用累积总和来执行此操作:

select t.*,
       sum(case when variance >= 4 then 1 else 0 end) over
            (order by date rows between unbounded preceding and 1 preceding
            ) as GroupNumber
from table t;