SQL更新列取决于其他列

时间:2019-03-19 08:31:17

标签: sql tsql

sequenceNo    IsPoint     PointNumber      PointSequenceNumber     IsCancel
1             1                 3168                1                 1
2             0                  NULL               2                 1
3             1                  3169               2                 1
4             1                  2806               3                 1
5             1                  33322              4                 1
6             1                  2807               5                 1
7             1                  2044               6                 1
8             1                  2046               7                 1
9             0                  NULL               8                 1
10            1                  27524              8                 1
11            1                   670               9                 0
12            1                   671               10                0
13            1                   672               11                0
14            0                   NULL              12                1
15            1                   1074              12                1
16            1                   10844             13                0
17            1                   1421              14                0

如果IsCancel设置为1,我需要根据IsCancel Column的值将PointNumber插入其他表中,我需要先插入第一个iscancel和最后一个IsCancel,但要依次插入

例如STARTPOINT =>高于序列号1168的序列号1并且Iscancel设置为1我需要将该点存储在其他表StartPoint中

ENDPOINT =>以上序列号点1074的15号且Iscancel设置为1,我需要将该点作为Endpoint存储在其他表中

TotalCANCELED =>列保持COUNT IsCancel,但仅当PointNumber不为NULL时

我需要根据上表使用以下数字更新其他表中的这些列

STARTPOINT         ENDPOINT             TOTALCANCEL

3168                 1074                  9

感谢社区

1 个答案:

答案 0 :(得分:0)

我发现这种逻辑很难遵循。如果我正确理解这一点,则可以使用聚合-尽管您需要稍作调整才能获得终点编号:

select max(case when PointSequenceNumber = 1 then pointnumber end) as startpoint,
       max(case when PointSequenceNumber = psn then pointnumber end) as endpoint,
       sum(case when isCancel = 1 and PointNumber is not null end) as totalCancel
from (select t.*,
             max(case when isCancel = 1 and PointNumber is not null then PointSequenceNumber end) over () as max_psn
      from t
     ) t;