gpt4 book ai didi

sql - T-SQL - 在单个表中查找 PK 的差异(自联接?)

转载 作者:行者123 更新时间:2023-12-04 13:38:44 24 4
gpt4 key购买 nike

我的情况是这样的。我有一个带有“组件”的pk“父级”的产品表数据看起来像这样

Parent(PK)    Component
Car1 Wheel
Car1 Tyre
Car1 Roof
Car2 Alloy
Car2 Tyre
Car2 Roof
Car3 Alloy
Car3 Tyre
Car3 Roof
Car3 Leather Seats

现在我想做的是一些查询,我可以输入两个代码并查看差异... IE 如果我输入“Car1”,“Car2”,它会返回类似的内容;

Parent       Component
Car1 Wheel
Car2 Alloy

因为这是两者之间的区别。如果我说“Car1”,“Car3”,我会期待;

Parent       Component
Car1 Wheel
Car3 Alloy
Car3 Leather Seats

非常感谢您对此事的帮助。

最佳答案

没有 GROUP BY 或 UNION:

create table Products (
Parent varchar(20) not null,
Component varchar(20) not null
)
insert into Products (Parent,Component)
select 'Car1','Wheel' union all
select 'Car1','Tyre' union all
select 'Car1','Roof' union all
select 'Car2','Alloy' union all
select 'Car2','Tyre' union all
select 'Car2','Roof' union all
select 'Car3','Alloy' union all
select 'Car3','Tyre' union all
select 'Car3','Roof' union all
select 'Car3','Leather Seats'
go
select
ISNULL (a.Parent,b.Parent) as Parent,
ISNULL (a.Component,b.Component) as Component
from
Products a
full outer join
Products b
on
a.Component = b.Component and
a.Parent = 'Car1' and
b.Parent = 'Car3'
where
(a.Parent = 'Car1' and b.Parent is null) or
(b.Parent = 'Car3' and a.Parent is null)

关于sql - T-SQL - 在单个表中查找 PK 的差异(自联接?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2956102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com