简体   繁体   中英

Self-join with distinct values

I have this table:

   name    code     value
--------------------------
| john  |  0001  |    1   |
| mary  |  0001  |    2   |
| mary  |  0002  |    3   |

What I would like to achieve is a result set that looks like this:

   name    code     value
--------------------------
| john  |  0001  |    1   |
| john  |  0002  |  NULL  |
| mary  |  0001  |    2   |
| mary  |  0002  |    3   |

In other words, I want the result to contain a row with a code of 0002 for john , which is missing from the table.

I would have thought something like this would have gotten me closer:

with x as (select distinct code from t)
select * from t left join x on x.code = t.code

but what I get is essentially the same table:

   name    code     value    value1
-------------------------- --------
| john  |  0001  |    1   |    1   |
| mary  |  0001  |    2   |    2   |
| mary  |  0002  |    3   |    3   |

Some additional thinking brought me to the conclusion that my solution couldn't possibly work anyway, since name would probably be NULL too, and I really need for it to show up.

I'm stumped, this looks easier than it actually is.

Can anyone shed some light?

You should also use a NAMES derived table, since in your method, which should be opposite of what it is(Either right join or replace t with x) won't return null values for the value.

So you first have to make a derived table containing all possible options of NAME|CODE , and then left join it to your original table.

SELECT t1.code,t2.name,t.value
FROM(SELECT DISTINCT code FROM t) t1
CROSS JOIN(SELECT DISTINCT name FROM t) t2
LEFT JOIN t
 ON(t2.name = t.name and t1.code = t.code)

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