简体   繁体   English

根据 sql 中的条件创建新列?

[英]Create new column based on condition in sql?

   PARENT_ID    ID   YR_MONTH    REWARD
1    1          11   201601        3
2    1          11   201605        9
3    1          13   201609        9
4    2          21   201601        6
5    2          21   201605        15
6    2          21   201609        9
7    3          31   201601        8
8    3          31   201605        9
9    3          32   201609        9
10   3          32   201610        9

I need to create a new column based Reward column.我需要创建一个基于奖励列的新列。 where Reward is 9 put 1 else 0 based on the condition.根据条件,奖励为 9 放置 1 否则为 0。

condition would be:条件是:

  1. for particular parent_id, id check if there is no higher reward than 9 in previous yr_month if yes then 0 else 1对于特定的 parent_id,id 检查上一年是否没有高于 9 的奖励如果是,则为 0,否则为 1

  2. only first 9 will be marked as 1 else 0只有前 9 个将被标记为 1,否则为 0

Expected results:预期成绩:

   PARENT_ID    ID   YR_MONTH    REWARD  REWARD_STATUS
1    1          11   201601        3         0
2    1          11   201605        9         1
3    1          13   201609        9         1
4    2          21   201601        6         0
5    2          21   201605        15        0
6    2          21   201609        9         0
7    3          31   201601        8         0
8    3          31   201605        9         1
9    3          32   201609        9         1
10   3          32   201610        9         0

I would use window functions:我会使用 window 函数:

select 
    t.*,
    case 
        when reward = 9 
        and sum(case when reward >= 9 then 1 else 0 end)  over(partition by parent_id order by yr_month) = 1
    then 1 else 0 end reward_status
from mytable t

The case expression returns 1 if: case表达式在以下情况下返回1

  • the reward of the current record has is 9当前记录的reward9

  • and there is not "previous" record for the same parent_id whose reward is equal or greater than 9并且reward等于或大于9的相同parent_id没有“先前”记录

If you are running MySQL, the case expression can be simplified as:如果你运行的是MySQL, case表达式可以简化为:

(
    reward = 9 
    and sum(reward >= 9)  over(partition by parent_id order by yr_month) = 1
) reward_status

Demo on DB Fiddle : DB Fiddle 上的演示

PARENT_ID | ID | YR_MONTH | REWARD | REWARD_STATUS
--------: | -: | -------: | -----: | ------------:
        1 | 11 |   201601 |      3 |             0
        1 | 12 |   201605 |      9 |             1
        1 | 13 |   201609 |     12 |             0
        2 | 21 |   201601 |      6 |             0
        2 | 22 |   201605 |      9 |             1
        2 | 23 |   201609 |      9 |             0
        3 | 31 |   201601 |     15 |             0
        3 | 32 |   201605 |      9 |             0
        3 | 33 |   201609 |     12 |             0
        3 | 34 |   201610 |      9 |             0

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

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