简体   繁体   中英

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.

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

  2. only first 9 will be marked as 1 else 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:

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:

  • the reward of the current record has is 9

  • and there is not "previous" record for the same parent_id whose reward is equal or greater than 9

If you are running MySQL, the case expression can be simplified as:

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

Demo on 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

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