简体   繁体   中英

SQL Server 2008R2: group number

Hello!

I have the first two columns of the following data in my table (let's call it storico):

IdZona  Inizio      number
24      1985-03-01    1
81      1988-12-01    2
21      1990-01-01    3
21      1992-02-01    3
79      1996-01-01    4
21      1996-11-01    5
21      1999-02-01    5 
21      2005-01-01    5 
21      2008-12-01    5

So the data has to be shown ordered by Date ("inizio"). For each date there is a certain value of IdZona. What I want to know is how to get the third column calculated by SQL Server 2008 R2. The Number has to increase each time another value in column idZona is detected. When going back to a value already given of idZona (pe se line 1996-11-01) the [number] value must not report a value already shown, but increase another time.

Hope, the task is clear.

Thanks in advance,

Klaus

It's a bit convoluted, but a recursive CTE can do it.

If the dates are guaranteed to be unique, it can be made a little simpler.

It's also one of those occasions where just iterating with a cursor might be faster and clearer.

With x as (
    Select Top 1 
        IdZona,
        Inizio,
        1 [number]
    From
        dbo.Storico
    Order By
        Inizio,
        IdZona
    Union All
    select
        y.IdZona,
        y.Inizio,
        y.[number]
    from (
        select
            s.IdZona,
            s.Inizio,
            case 
                when s.IdZona = x.IdZona Then x.[number] 
                else x.[number] + 1 
            end [number],
            row_number() over (order by s.Inizio, s.IdZona) rn
        From
            dbo.Storico s,
            x
        Where
            s.Inizio > x.Inizio or (
                s.Inizio = x.Inizio and 
                s.IdZona > x.idZona
            )
        ) y
    Where
        y.rn = 1
)           
Select 
    * 
From 
    x

Example SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM