SQL

时间:2016-05-18 08:06:29

标签: sql sql-server

在下表中,我将计算列S:

 Week     L       C1      C2      C3      C4      C5      C6      S
   1    L1=3      258     141     140      21      51     197    S1=1000
   2       7      291     261      64     275      72     249
   3       1      287     164      99     222     149     172
   4       3      163     193    A=200     95     170      51
   5       4      193      11     271    B=300    199      26
   6    L6=2      213     120      53     210    C=400     43    S6=507 
   7       5       36     208     243     163     126    D=100
   8       3      174      56     282     274     214      222
   9       1       63     295    M=222    153     136      173
   10      4      191     114     195     N=8      28      188
   11      3      125     293      38      56    O=277     11

作为通用公式,我想根据以下公式找到S列:

如果L> = 3,则S = C3在三周后+ C4在四周后+ C5在五周后+ C6在六周后。例如,S1 = A + B + c + D = 1000

如果L < 3,S = C3三周后+ C4四周后+ C5五周后。例如S6 = M + N + O = 507.

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:3)

第一个出现在我脑海中:

SELECT c1.*, 
        CASE WHEN c1.L >=3 THEN ISNULL(c2.C3,0) + ISNULL(c3.C4,0) + ISNULL(c4.C5,0) + ISNULL(c5.C6,0)
        ELSE ISNULL(c2.C3,0) +ISNULL(c3.C4,0) + ISNULL(c4.C5,0) END as S
FROM YourTableName c1
LEFT JOIN YourTableName c2 
    ON c1.[Week] + 3 = c2.[week]
LEFT JOIN YourTableName c3
    ON c2.[Week] + 1 = c3.[week]
LEFT JOIN YourTableName c4
    ON c3.[Week] + 1 = c4.[week]
LEFT JOIN YourTableName c5
    ON c4.[Week] + 1 = c5.[week]

输出:

Week    L   C1  C2  C3  C4  C5  C6  S
1       3   258 141 140 21  51  197 1000
2       7   291 261 64  275 72  249 829
3       1   287 164 99  222 149 172 430
4       3   163 193 200 95  170 51  841
5       4   193 11  271 300 199 26  474
6       2   213 120 53  210 400 43  507
7       5   36  208 243 163 126 100 251
8       3   174 56  282 274 214 222 38
9       1   63  295 222 153 136 173 0
10      4   191 114 195 8   28  188 0
11      3   125 293 38  56  277 11  0

修改

对于SQL Server 2012,您可以使用https://developer.paypal.com/docs/classic/adaptive-payments/integration-guide/APIntro/

SELECT  *,
        CASE WHEN L >= 3 THEN 
            LEAD(C3, 3, 0) OVER (ORDER BY [Week]) +
            LEAD(C4, 4, 0) OVER (ORDER BY [Week]) +
            LEAD(C5, 5, 0) OVER (ORDER BY [Week]) +
            LEAD(C6, 6, 0) OVER (ORDER BY [Week]) 
        ELSE 
            LEAD(C3, 3, 0) OVER (ORDER BY [Week]) +
            LEAD(C4, 4, 0) OVER (ORDER BY [Week]) +
            LEAD(C5, 5, 0) OVER (ORDER BY [Week])
        END as S
FROM YourTableName 

输出将是相同的。