SQL Server连续值分组

时间:2019-06-19 08:23:14

标签: sql sql-server

我有一个SQL Server 2014表,其中包含给定供应商的服务记录。我需要按Supplier_ID和连续的ServiceDay值进行分组,然后输出min(CostingService_ID)。

Data and schema as SQL Fiddle example

这是原始的SQL数据示例

CostingService_ID   Supplier_ID ServiceDay
722250  6191    1
722251  6759    2
722252  6363    3
722253  6903    4
722254  6301    5
722255  6301    6
722256  7667    7
722257  7195    8
722258  6191    10
722259  6191    11
722260  6191    12
722261  6191    13
722262  7195    9

所以在这种情况下,我想输出

722250  
722251  
722252  
722253  
722254  
722256  
722257  
722258  

在这种情况下,普通的分组依据不起作用。

6 个答案:

答案 0 :(得分:2)

如果我正确理解的话,您需要这样做:

  select CostingService_ID from (   
     select CostingService_ID ,  row_number() over(partition by Supplier_ID order by ServiceDay) rn from t
  ) t
  where rn = 1
  order by CostingService_ID

答案 1 :(得分:1)

下面的脚本应该为您提供每个Supplier_ID的MIN CostingService_ID

SELECT MIN(CostingService_ID)
FROM your_table
GROUP BY Supplier_ID

答案 2 :(得分:1)

请尝试以下查询:

SELECT MIN(CostingService_ID) FROM (
  SELECT CostingService_ID,
         ROW_NUMBER() OVER (ORDER BY ServiceDay) -
         ROW_NUMBER() OVER (PARTITION BY Supplier_ID ORDER BY ServiceDay) grp
  FROM CostingService
) a GROUP BY grp

您需要使用行号之间的差异来检查特定数字是否连续。

答案 3 :(得分:0)

使用row_number()函数

SELECT CostingService_ID
FROM (SELECT CostingService_ID, ROW_NUMBER() OVER (PARTITION BY Supplier_ID ORBER BY CostingService_ID) AS rownum FROM CostingService) AS a
where rownum = 1

答案 4 :(得分:0)

如果我对您的理解正确,那么您就需要像

select *
from CostingService cs
where not exists(
    select * from CostingService
    where Supplier_ID = cs.Supplier_ID and ServiceDay = cs.ServiceDay - 1
)

答案 5 :(得分:0)

检查这种方法,我测试了为同一供应商添加非连续天数,并且可以正常工作。

;with consecutives as (
    select Supplier_ID , ServiceDay
    from @t t1
    where not exists (select 1 from @t where Supplier_ID  = t1.Supplier_ID  and ServiceDay = t1.ServiceDay -1)
)
select t1.Supplier_ID , t1.ServiceDay, t2.ServiceDay as nextServiceDay, CostingService_ID
from consecutives t1
outer apply (
    select top 1 n.ServiceDay from consecutives n where n.Supplier_ID  = t1.Supplier_ID  and n.ServiceDay > t1.ServiceDay order by n.ServiceDay
) t2
outer apply (
    select min(CostingService_ID) CostingService_ID from @t where Supplier_ID  = t1.Supplier_ID  and ServiceDay between t1.ServiceDay and isnull(t2.ServiceDay - 1, t1.ServiceDay)
) t3