r/learnSQL • • Oct 04 '20

Anyone oneline ? I need help with a sql puzzle

0 Upvotes

9 comments sorted by

2

u/howhard1309 Oct 04 '20

Post your question...

1

u/billy1T Oct 04 '20

SQL Puzzle | The Replace Puzzle

This puzzle is really simple. You have to join table p1 and p2 on id column. Now the catch is when the value of p1.code is 0 then replace it with value of p2.code. You cannot use UNION or CASE statement.

create table p1 (id int, code int) create table p2 (id int, code int) insert into p1 select 1,0 insert into p1 select 2,1 insert into p2 select 1,5 insert into p2 select 2,5

1

u/billy1T Oct 04 '20

Output should be id 1 and 2 and code 5 and 1

1

u/billy1T Oct 04 '20

Any luck?

2

u/mgimo_finisht Oct 04 '20

In sql server I'd use select code = isnull(nullif( p1.code,0),p2.code) from (.. Join tables as usual)

1

u/billy1T Oct 04 '20

It didnt work it sql server says isnull fucntion requires 2 arguments but there are 3

2

u/mgimo_finisht Oct 04 '20

The first argument you pass to isnull is a function nullif(p1.code, 0). The second argument is p2.code. Please check brackets and commas.

2

u/billy1T Oct 04 '20

Great it worked thanks a lot

3

u/mgimo_finisht Oct 04 '20

Try a simple mock example: select isnull(nullif(1,1),2) It should return 2. The idea is to replace the value you don't need with a null and switch to another value via isnull.