查找用户及其缺失值

问题描述 投票:1回答:1

我有一个如下表:

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

感谢您的帮助。

sql sql-server tsql left-join
1个回答
0
投票

您可以cross join不同的useridval,然后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

Demo on DB Fiddle

用户名|值-----:| -:1 | 42 | 1个2 | 2
© www.soinside.com 2019 - 2024. All rights reserved.