[英]SQL Increment number in select statement
I have an issue where I need group a set of values and increase the group number when the variance between 2 columns is greater than or equal to 4, please see below. 我有一个问题,当两列之间的方差大于或等于4时,我需要对一组值进行分组并增加组数,请参见下文。
UPDATE: I added a date column so you can view the order, but I need the group to update based off of the variance not the date. 更新:我添加了一个日期列,以便您可以查看订单,但是我需要根据差异而不是日期来更新组。
+--------+-------+-------+----------+--------------+ | 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 | +--------+-------+-------+----------+--------------+
The group number is simply the number of times that 4 or greater appears in the variance
column. 组号就是variance
列中出现4个或更多的次数。 You can get this using a correlated subquery: 您可以使用相关的子查询获取此信息:
select t.*,
(select 1 + count(*)
from table t2
where t2.date < t.date and t2.variance >= 4
) as GroupNumber
from table t;
In SQL Server 2012+, you can also do this using a cumulative sum: 在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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.