[英]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. 换句话说,我希望结果包含
john
的code
为0002
的行,表中缺少该行。
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. 一些额外的想法让我得出结论,我的解决方案无论如何都无法工作,因为
name
也可能是NULL
,我真的需要它出现。
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. 您还应该使用
NAMES
派生表,因为在您的方法中,它应该与它的相反(无论是右连接还是用x替换t)都不会返回值的空值。
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. 因此,您首先必须创建一个包含
NAME|CODE
所有可能选项的派生表,然后将其连接到原始表。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.