按范围分组并具有子字符串的后续结果

时间:2019-02-20 23:14:08

标签: sql sql-server

具有以下数据结构:

UniqueAssignedNumber   | UniqueEntity

6371170100010001       | a
6371170100010011       | a
6371170100010021       | a
6371170100010031       | b
6371170100010041       | b
6371170100010051       | b
6371170100010061       | a
6371170100010071       | a

我需要按范围对子字符串(UniqueAssignedNumber,7、4)和子字符串(UniqueAssignedNumber,11、5)进行分组 问题是,您可以看到这些范围不在后面。

这是我想出的最好结果:

select
substring(t.numero, 7, 4) as a, 
min(substring(t.numero, 11, 5)) as rangefrom,
max(substring(t.numero, 11, 5)) as rangeto,
entity


from table t
where substring(t.numero, 0, 7) = '637117'
group by (substring(t.numero, 7, 4))

但是我得到以下结果:

0100    53001   54000   CLUB IN CAPITAL
0100    77806   78000   CLUB IN LA PLATA
0100    08663   99999   CLUB IN MAR DEL PLATA
0100    43001   80000   CLUB IN MENDOZA
0100    78001   78999   CLUB IN MONTE

我需要多个范围。

赞:

0100    53001   54000   CLUB IN CAPITAL
0100    77806   78000   CLUB IN LA PLATA
0100    08663   99999   CLUB IN MAR DEL PLATA
0100    43001   44000   CLUB IN MENDOZA
0100    77000   78000   CLUB IN MENDOZA
0100    79000   80000   CLUB IN MENDOZA
0100    78001   78999   CLUB IN MONTE

1 个答案:

答案 0 :(得分:0)

对预期结果进行排序时,还会出现另一个问题,显示列范围与“ 77000 78000 CLUB IN MENDOZA”和“ 77806 78000 CLUB IN LA PLATA”重叠,它们各自以78000结尾。

“ UniqueEntity”列中是否包含俱乐部名称?如果不是,那么它们又来自另一个联接表?

0100    08663   99999   CLUB IN MAR DEL PLATA
0100    43001   44000   CLUB IN MENDOZA
0100    53001   54000   CLUB IN CAPITAL
0100    77000   78000   CLUB IN MENDOZA
0100    77806   78000   CLUB IN LA PLATA
0100    78001   78999   CLUB IN MONTE
0100    79000   80000   CLUB IN MENDOZA

2019年2月21日星期四21:30-这是一些可以使用的SQL,具体取决于表的DDL是什么。将我的[StackOver]。[dbo]。[GroupByRanges]更改为您自己的表。

--SET NOCOUNT ON

DECLARE cur CURSOR FOR SELECT 
     substring(t.numero, 1, 7) as ClubArea
    ,substring(t.numero, 8, 4)  as ClubGroup
    ,substring(t.numero, 12, 5) as ClubSeq
    ,t.entity
    From [StackOver].[dbo].[GroupByRanges] as t
    Where substring(t.numero, 1, 7) = '6371170'
    Order By t.numero

OPEN cur

Declare @minClubSeq NVARCHAR(255), @maxClubSeq NVARCHAR(255), @nextClubSeq NVARCHAR(255), @prevEntity NVARCHAR(255)
DECLARE @returnTable TABLE (rminClubSeq NVARCHAR(255), rmaxClubSeq NVARCHAR(255), rnextClubSeq NVARCHAR(255),  rEntity NVARCHAR(255))
SET @prevEntity = ''
DECLARE @skip  NVARCHAR(255), @ClubSeq NVARCHAR(255),  @entity NVARCHAR(255)

FETCH NEXT FROM cur INTO @skip, @skip, @ClubSeq, @entity
WHILE @@FETCH_STATUS = 0
BEGIN
    If ( (@prevEntity <> @entity) ) 
        BEGIN
            Insert INTO @returnTable Select @minClubSeq, @maxClubSeq, @ClubSeq,  @prevEntity
            Set @prevEntity = @entity
            Set @minClubSeq = @ClubSeq
        END
    Set @maxClubSeq = @ClubSeq
    FETCH NEXT FROM cur INTO @skip, @skip, @ClubSeq, @entity 
END
        Insert INTO @returnTable Select @minClubSeq, @maxClubSeq, @ClubSeq,  @prevEntity

CLOSE cur
DEALLOCATE cur


Select * From @returnTable Where rEntity > ''