简体   繁体   English

您将如何使用SQL Server 2005做到这一点?

[英]How would you do this using SQL Server 2005?

Let's say I have a table table1 with the following structure: 假设我有一个具有以下结构的表table1

  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. 您可能会看到,该表的每个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. -summarystory:=该变量是为日期在0507之间的那些行计算的,并且是最后三行的变量v3的总和。

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 . 让我更好地解释一下:前两行( date 03和04)必须具有NULL值,但具有date=05的行是最后三个v3值的总和,即89+9+6=104 Likewise, the row having date=06 must be equal to 9+6+9=24 . 同样,具有date=06的行必须等于9+6+9=24 This have to be done for each id and for each date. 必须针对每个ID和每个日期执行此操作。

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 ). VcountYN:=每行的Y数(仅基于变量v1v2 )。 So. 所以。 for instance, for the first row it would be VcountYN=1. 例如,对于第一行,它将为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 http://sqlfiddle.com/#!6/a1c45/2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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