我正在尝试通过检查某些条件从表中获取数据:
表格详细信息
CODE | PRODUCT |
FWD 4X4 | PROD1 |
表头
CODE | GROUP |
FWD | AAA |
4X4 | AAA |
FWD | CCC |
预期结果
CODE | PRODUCT | GROUP |
FWD 4X4 | PROD1 | AAA |
因为组AAA具有两个代码:FWD和4X4。组CCC不合格,因为只有一个代码。 是否可以通过SQL查询做到这一点?我已经尝试过使用分割字符串和交叉应用,即使关闭也不行。
如果过于复杂,也许我会使用编程语言。由于我对SQL不太满意。 代码组合也可能变得更长(3个单词或更多)。
谢谢。
答案 0 :(得分:0)
如果您的SQL Server版本是17,请使用String_agg函数
select a.code,a.prod,a.group from tabledetail a
inner join
(SELECT [group], STRING_AGG (code, ' ') as c
FROM tableheader
GROUP BY [group]) b on a.code=b.c
对于较低版本,您可以使用填充功能:
select a.code,a.prod,a.group from tabledetail a
inner join
(SELECT [group], c= STUFF(
(SELECT ' ' + code
FROM tableheader t1
WHERE t1.id = t2.id
FOR XML PATH (''))
, 1, 1, '') from tableheader t2
group by [group])b on a.code=b.c
答案 1 :(得分:0)
构建架构
create table Detail (CODE varchar(300) ,PRODUCT varchar(100) );
insert into Detail values ('FWD 4X4','PROD1');
insert into Detail values ('FWD','PROD2');
insert into Detail values ('FWD 4X4 FM','PROD3');
create table Header (CODE varchar(300) ,[GROUP] varchar(100) );
insert into Header values ('FWD','AAA');
insert into Header values ('4X4','AAA');
insert into Header values ('FWD','CCC');
insert into Header values ('4X4','DDD');
insert into Header values ('FM','DDD');
insert into Header values ('FWD','DDD');
解决方案sql
select d.CODE, d.PRODUCT, h.[GROUP]
from Detail d
inner join Header h on CHARINDEX(' ' +h.code+ ' ', ' ' + d.Code + ' ') > 0
inner join (
select [Group],count(Code) GroupCodesCount
from Header
Group By [Group]
) GroupCodes on GroupCodes.[Group] = h.[GROUP]
group by d.CODE, d.PRODUCT, h.[GROUP],GroupCodesCount
having len(d.CODE) - len(replace(d.CODE, ' ', '')) +1 = count(h.code) and count(h.code) = GroupCodesCount
输出结果
CODE PRODUCT GROUP
FWD PROD2 CCC
FWD 4X4 PROD1 AAA
FWD 4X4 FM PROD3 DDD
当明细表在组CHARINDEX(' ' +h.code+ ' ', ' ' + d.Code + ' ') > 0
上包含至少一个代码时,我将其与Header联接在一起,然后按产品和组对它进行联接以对每个组视图的代码进行计数,然后过滤结果组以返回组完全符合组代码having len(d.CODE) - len(replace(d.CODE, ' ', '')) +1 = count(h.code) and count(h.code) = GroupCodesCount
希望有帮助