我有2个表Employee and Skills
,其中包含以下字段:
员工:Id,Name,Location
技能:Id,Skills
员工数据:
Id Name Location
7 Abc London
8 Xyz London
9 Xyz USA
10 Abc USA
技能:
Id skills EmployeeId
12 AAA Xyz 7
13 BBB 7
14 CCC 7
15 AAA 8
16 BBB 8
17 CCC 8
18 AAA 9
19 BBB 9
20 CCC 9
21 AAA 10
22 BBB 10
20 CCC 10
现在,我想获得那些Name is Abc
,Location is London and Skills is both AAA and BBB
的员工的技能,但我想要单输出,如下所示:
Skills
10,11
这是我的疑问:
select S.Id from Employee E inner join
Skills S on E.Id=s.EmployeeId
where (E.Name='Abc' and E.Location='London'
and s.skills='AAA') and (E.Name='Abc' and E.Location='London'
and s.skills='BBB')
但我输错了。
答案 0 :(得分:1)
您可以使用STUFF
:
Select Stuff
(
(
Select ',' + Convert(Varchar, S.Id)
From Employee E
Join Skills S On S.EmployeeId = E.Id
Where E.Name = 'Abc'
And E.Location = 'London'
And S.Skills In ('AAA', 'BBB')
For Xml Path ('')
), 1, 1, ''
) As Skills
编辑:SQL Fiddle似乎暂时不想与我合作,但使用以下数据(来自OP),它确实得到了正确的结果:
Create Table Skills
(
Id int,
skills varchar (3),
employeeid int
);
Create Table Employee
(
Id int,
Name varchar (10),
location varchar (10)
);
insert skills values
(10 ,'AAA', 1),
(11 ,'BBB', 1),
(13 ,'CCC', 1),
(14 ,'DDD', 1);
insert employee values
( 1 ,'Abc' , 'London'),
( 2 ,'Xyz', 'Uk');
Select Stuff
(
(
Select ',' + Convert(Varchar, S.Id)
From Employee E
Join Skills S On S.EmployeeId = E.Id
Where E.Name = 'Abc'
And E.Location = 'London'
And S.Skills In ('AAA', 'BBB')
For Xml Path ('')
), 1, 1, ''
) As Skills
编辑#2 新数据;相同的查询:
Create Table Skills
(
Id int,
skills varchar (3),
employeeid int
);
Create Table Employee
(
Id int,
Name varchar (10),
location varchar (10)
);
insert skills values
(12 ,'AAA', 7 ),
(13 ,'BBB', 7 ),
(14 ,'CCC', 7 ),
(15 ,'AAA', 8 ),
(16 ,'BBB', 8 ),
(17 ,'CCC', 8 ),
(18 ,'AAA', 9 ),
(19 ,'BBB', 9 ),
(20 ,'CCC', 9 ),
(21 ,'AAA', 10 ),
(22 ,'BBB', 10 ),
(20 ,'CCC', 10 );
insert employee values
(7 ,'Abc', 'London' ),
(8 ,'Xyz', 'London' ),
(9 ,'Xyz', 'USA' ),
(10 ,'Abc', 'USA' );
Select Stuff
(
(
Select ',' + Convert(Varchar, S.Id)
From Employee E
Join Skills S On S.EmployeeId = E.Id
Where E.Name = 'Abc'
And E.Location = 'London'
And S.Skills In ('AAA', 'BBB')
For Xml Path ('')
), 1, 1, ''
) As Skills
这次的结果是12,13
- 根据您的条件是正确的:
员工7
是来自Abc
London
12
的{{1}}唯一,13
和AAA
BBB
技能。