根据小时查找连续行并按日期分组

时间:2015-12-17 07:45:22

标签: sql sql-server-2008 tsql

我目前有一张包含小时和日期的表格。我正在尝试查找“cnt”列不等于0的每个日期的连续小时数

对于这些数据:

 Date       Hour V1 V2 Cnt Cons
 ------------------------------
 2015-12-15  1   a  b   1   3
 2015-12-15  2   a  b   2   3
 2015-12-15  2   b  b   2   1
 2015-12-15  3   a  b   3   3
 2015-12-15  3   b  b   2   1
 2015-12-15  4   a  b   0   0
 2015-12-15  5   a  b   1   2
 2015-12-15  6   a  b   1   2

根据上表,日期2015-12-15有2个实例,其中连续小时cnt不等于0(1-3,5-6)

只有V1和V2不同时才会发生重复小时

我想达到这个输出:

Upload failed

You uploaded an APK that is signed with a different certificate to your previous APKs.
You must use the same certificate.

Your existing APKs are signed with the certificate(s) with fingerprint(s):
[ SHA1: 33:00:07:BA:2B:DC:9C:29:B0:B9:54:F1:AA:C9:9C:00:6A:D0:93:35 ]

and the certificate(s) used to sign the APK you uploaded have fingerprint(s):
[ SHA1: 60:BB:1D:CA:5F:5A:0B:7C:62:8B:11:CE:88:2D:FC:8F:FA:ED:D6:FD ]

1 个答案:

答案 0 :(得分:0)

既然你已经编辑了你的问题,它就表明你不想只在一天内查看和计算,而是在一天之内+ v1 + v2。

如果我一天只选择一个v1 / v2对,除了Cnt = 0,那么我会得到相应的时间进行调查,例如: 1,2,5,6,8,9。因此可能存在间隙(实际间隙或Cnt = 0间隙),但在这样的组内没有重复。如果我从值中减去此结果中的位置,我会连续几小时获得组密钥:

hour   pos  hour-pos=groupkey
1      1    1-1=0
2      2    2-2=0
5      3    5-3=2
6      4    6-4=2
8      5    8-5=3
9      6    9-6=3

这使用我得到:

select 
  date, hour, v1, v2, 
  count(*) over (partition by date, v1, v2, groupkey) as cons
from
(
  select 
    mytable.*, 
    hour - row_number() over (partition by date, v1, v2 order by hour) as groupkey
  from mytable
  where cnt <> 0
) grouped
union all
select date, hour, v1, v2, 0 as cons
from mytable
where cnt = 0
order by date, hour, v1, v2;