简体   繁体   中英

How would you do this using SQL Server 2005?

Let's say I have a table table1 with the following structure:

  id date v1   v2  v3  v4 ... vn
  ------------------------------
  1   03   Y    N  89  77 ... x
  1   04   N    N  9   7  ... i
  1   05   N    Y  6   90 ... j
  1   06   N    Y  9   34 ... i
  1   07   N    Y  0   88 ... i
  2   03   N    N  9   77 ... f
  2   04   Y    Y  90  7  ... y
  2   05   Y    N  6   90 ... v
  2   06   N    Y  9   34 ... i
  2   07   N    N  10  88 ... i

As you might see, the table has five rows for each id. I'd like to create two new columns:

-summarystory:= This variable is computed for those rows having the date between 05 and 07 and is the sum of the variable v3 for the last three rows.

Let me explain this better: the first two rows ( date 03 and 04) must have NULL values, but the row having date=05 is the sum of the last three v3 values, ie, 89+9+6=104 . Likewise, the row having date=06 must be equal to 9+6+9=24 . This have to be done for each id and for each date.

This is the desired result:

  id  date v3  summarystory
  -------------------------
  1    03  89     NULL
  1    04  9      NULL
  1    05  6      104
  1    06  9      24
  1    07  0      15
  2    03  9      NULL
  2    04  90     NULL
  2    05  6      105
  2    06  9      105
  2    07  10     25
  • VcountYN:= the number of Y for each row (based only on variables v1 and v2 ). So. for instance, for the first row it would be VcountYN=1. This variable must be computed for all the rows.

Any help is much appreciated.

Here's how to do the computations. Turning it into the new table is left as an exercise:

-- SQL 2012 version
Select
  t.id,
  t.[date],
  Case When [Date] Between 5 And 7 Then 
    Sum(v3) over (
      partition by 
        id 
       order by 
         [date]
       rows between 
         2 preceding and current row
    ) Else Null End,
  Case When v1 = 'Y' Then 1 Else 0 End +
    Case When v2 = 'Y' Then 1 Else 0 End
From
  table1 t;

-- SQL 2005 version
Select
  t1.id,
  t1.[date],
  Case When t1.[date] Between 5 And 7 Then t1.v3 + IsNull(t2.v3, 0) + IsNull(t3.v3, 0) Else Null End,
  Case When t1.v1 = 'Y' Then 1 Else 0 End +
    Case When t1.v2 = 'Y' Then 1 Else 0 End
From
  table1 t1
    Left Outer Join
  table1 t2
    On t1.id = t2.id and t1.[date] = t2.[date] + 1
    Left Outer Join
  table1 t3
    On t2.id = t3.id and t2.[date] = t3.[date] + 1

http://sqlfiddle.com/#!6/a1c45/2

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