我有一个如下表:
declare @t as table
(
userid int,
val int
)
insert into @t(userid, val) values
(1,1),
(1,2),
(1,3),
(2,3),
(2,4),
(3,1),
(3,2),
(3,3),
(3,4),
(6,1),
(6,2),
(6,3),
(6,4)
userid 3和6在val列中具有所有可能的值(1到4),但不是所有用户。我希望使用LEFT JOIN从上表中找到用户及其缺失值,上表的查询结果应如下所示:
userid, val
1, 4
2, 1
2, 2
感谢您的帮助。
您可以cross join
不同的userid
和val
,然后left join
包含原始表的结果数据集以找到丢失的元组:
select u.userid, v.val
from (select distinct userid from @t) u
cross join (select distinct val from @t) v
left join @t t on t.userid = u.userid and t.val = v.val
where t.userid is null
order by u.userid, v.val
用户名|值-----:| -:1 | 42 | 1个2 | 2