0

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 (p.e. 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

4

1 回答 1

2

这有点令人费解,但递归 CTE 可以做到。

如果保证日期是唯一的,则可以简化一些。

这也是仅使用光标进行迭代可能更快、更清晰的情况之一。

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

于 2013-11-05T23:49:01.540 回答