0

I am having an issue. I need to creat a new column based on row values. so my table is

id | Name   |  status |   
-+-------+-------
1  | ANNA   |  M      | 
1  | anna   | null    | 
2  | DIVA   | null    | 
2  | diva   | null    |

based on the status column I want to create a column new_status. where it will check if the id is same and the value of any row of status column is non null then the new column would have that non null value otherwise it will be null. like the image below

id | Name   |  status | new_status
--+------+-------+------------
1  | ANNA   |  M      | M
1  | anna   | null    | M
2  | DIVA   | null    | null
2  | diva   | null    | null

please help me with this.

2
  • Please post data as text not images. What rdbms are you using: mysql, sql server etc? Commented Mar 17, 2022 at 12:22
  • i am using mysql. I have tried to post data as text but it becomes very messy. that's why post it as image. Commented Mar 17, 2022 at 12:25

1 Answer 1

1

Two comments, as you are not supplying the DBMS you use:

  1. I assume your DBMS supports the LAST_VALUE(... IGNORE NULLS) OLAP function
  2. I am shamelessly taking advantage of the fact that capital letters come before small letters. Otherwise, you would need a third, sequence column within the id values; SQL tables are not sorted by default, and I would PARTITION BY id ORDER BY sequence) then.

But, otherwise:

\pset null (null)
WITH
indata(id,nam,status) AS (
            SELECT 1,'ANNA','M'
  UNION ALL SELECT 1,'anna',NULL
  UNION ALL SELECT 2,'DIVA',NULL
  UNION ALL SELECT 2,'diva',NULL
)
SELECT
  *
, LAST_VALUE(status IGNORE NULLS) OVER(PARTITION BY id ORDER BY nam) AS new_status
FROM indata
ORDER BY id,nam;

-- out Null display is "(null)".
-- out  id | nam  | status | new_status 
-- out ----+------+--------+------------
-- out   1 | ANNA | M      | M
-- out   1 | anna | (null) | M
-- out   2 | DIVA | (null) | (null)
-- out   2 | diva | (null) | (null)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.