1

I have a table with the following:

  |    A    |    B    |  
  |  blue   |  null   |
  |  orange |  null   | 
  |  orange |   x     | 
  |  blue   |   y     |

I would like to achieve this:

  |    A    |    B    |    C    |
  |  blue   |  null   |    y    |
  |  orange |  null   |    x    |
  |  orange |   x     |    x    |
  |  blue   |   y     |    y    |

The only values that orange can take in column B are null or x, same for blue (null or y) Apologies if this has already been answered, I couldn't find it anywhere on the site.

Thanks

1
  • 1
    This could be a simple join, except that there are cases you didn't show or mention. What if orange has another row 'orange', 'z' ? Which value 'x' or 'z' do you want to show in the orange row containing null? Commented Oct 16, 2021 at 12:53

3 Answers 3

3

Assuming you have analytic functions available, you may simply try:

SELECT A, B, MAX(B) OVER (PARTITION BY A) AS C
FROM yourTable;

We could also use an aggregation approach:

SELECT t1.A, t1.B, t2.MAX_B AS C
FROM yourTable t1
INNER JOIN
(
    SELECT A, MAX(B) AS MAX_B
    FROM yourTable
    GROUP BY A
) t2
    ON t2.A = t1.A
Sign up to request clarification or add additional context in comments.

Comments

0

above answer would work. I added my solution:

SELECT c1.A, c1.B, c2.B
FROM colors c1
INNER JOIN 
(SELECT DISTINCT A, B
 FROM colors 
 where B is NOT NULL) c2
ON c1.A =  c2.A

Comments

0

I wanted to ask here because there is a similar situation. my code is as below. but my problem is that my query is still not finished after 15 hours since my file is quite large. Maybe this is normal for SQL or I should optimize my query?

(3.541.265 rows - PostgreSQL)

UPDATE clean_table_v01 AS t1
SET start_station_name = (
    SELECT start_station_name
    FROM clean_table_v01 AS t2
    WHERE t1.start_station_id = t2.start_station_id
      AND start_station_name NOTNULL
    LIMIT 1)
WHERE start_station_name ISNULL;

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.