SQL Server间隔号

时间:2014-03-05 09:34:18

标签: sql sql-server

我有一个非常简单的表,有三列和下一个数据:

+------+---------+---------+
| Cod  |  Value  |  status |
+------+---------+---------+
| 1    |  1      |  1      |
| 1    |  2      |  1      |
| 1    |  3      |  1      |
| 1    |  4      |  0      |
| 1    |  5      |  0      |
| 1    |  6      |  1      |
| 1    |  7      |  1      |
+------+---------+---------+

我需要获得每个代码的连续数字间隔。我寻求的结果是:

+------+----------------+----------------+---------+
| cod  |  min_val_intv  |  max_val_intv  |  status |
+------+----------------+----------------+---------+
| 1    |  4             |  5             |  0      |
| 1    |  1             |  3             |  1      |
| 1    |  6             |  7             |  1      |
+------+----------------+----------------+---------+

我的问题不是得到那个结果。我尝试使用函数min,max和group by:

SELECT cod, MIN(Value) AS min_val_intv, MAX(Value) AS max_val_intv, status
FROM test_table
GROUP BY status, cod
有人可以帮助我。

问候。

2 个答案:

答案 0 :(得分:3)

尝试此查询:

with tab1 as
(select table1.*,
 ROW_NUMBER() OVER(ORDER BY (SELECT 1)) -
 ROW_NUMBER() OVER(PARTITION BY status order by Cod) rn1,
 ROW_NUMBER() OVER(ORDER BY (SELECT 1)) -
 ROW_NUMBER() OVER(order by value) rn2
from table1)
select cod,min(value) min_val,max(value) max_val,status 
from tab1
group by cod,status,rn1,rn2;

SQL Fiddle

答案 1 :(得分:0)

有了Hamidreza的好建议,我几乎有了目标,我把查询能够审查:

SQL Fiddle

查询:

with tab1 as 

(选择table1。*,ROW_NUMBER()OVER(按鳕鱼排序) - ROW_NUMBER()OVER(按鳕鱼的值分配状态顺序,值)rn 来自table1)

选择cod,min(value)min_val,max(value)max_val,tab1 group by cod,status,rn的状态;

结果几乎是完美的但是因为如果位置发生变化,我会重新定位记录,如下面的链接SQL Fiddle。结果不太正确。

有人提出要解决这个问题吗?

问候。