这是表格的外观,此处的Empid和idnumber对于每个员工都是唯一的,并且一个员工可以拥有多个具有不同证件编号的证件。
现在,我想过滤以6542和3214开头的徽章的员工,即同时带有6542和3214的徽章的员工
谢谢
更新1
有些记录从6542或3214开始只有一个徽章。但是我只需要带有两个徽章的员工。
答案 0 :(得分:1)
就像在徽章字段上一样使用
Select empid, name
from TableName
where badge like '6542%' or badge like '3214%'
group by empid, name
having count(*)>1
答案 1 :(得分:1)
执行GROUP BY
,使用HAVING
确保两个徽章:
select empid, name
from Table
where badge like '6542-%' or badge like '3214-%'
group by empid, name
having count(distinct badge) > 1
或使用INTERSECT
:
select empid, name from Table where badge like '6542-%'
intersect
select empid, name from Table where badge like '3214-%'
答案 2 :(得分:0)
这将起作用:
select empid from table_name where regexp_like(Badge,'^(6542)(.*)$')
intersect
select empid from table_name where regexp_like(Badge,'^(3214)(.*)$');
等效的SQL Server:
select empid from table_name where PATINDEX ('^(6542)(.*)$',Badge) !=0
intersect
select empid from table_name where PATINDEX ('^(6542)(.*)$',Badge) !=0
答案 3 :(得分:0)
我们可以将COUNT DISTINCT
中的CASE
与HAVING
一起使用,如下所示
DECLARE @test AS TABLE(EMPID INT, Badge VARCHAR(50), idNumber INT, EName VARCHAR(50))
INSERT INTO @test VALUES
(1148, '6542-74488', 66448, 'Adam Jhon'),
(1148, '642-8562', 66448, 'Adam Jhon'),
(1148, '3214-52874', 66448, 'Adam Jhon'),
(1149, '3214-45220', 209541, 'Tom Koyaski'),
(1150, '3214-23134', 63339, 'Shirin Abdulla'),
(1151, '3214-42355', 65498, 'Linda Jhon'),
(1151, '6542-2546', 65498, 'Linda Jhon'),
(1152, '3214-47632', 208673, 'Gayeth'),
(1153, '6542-73085', 83209, 'Maria Smith'),
(1153, '3214-58073', 65498, 'Maria Smith'),
(1154, '3214-26735', 208673, 'Ayan Jacob'),
(1155, '642-26739', 53959, 'Wo Li')
SELECT empid, Ename
FROM @test
WHERE badge LIKE '6542%' OR badge LIKE '3214%'
GROUP BY empid, Ename
HAVING COUNT (DISTINCT(CASE WHEN badge like '6542%' THEN 1
WHEN badge LIKE '3214%' THEN 2 END))>1
输出:
empid Ename
1148 Adam Jhon
1151 Linda Jhon
1153 Maria Smith
答案 4 :(得分:0)
只需这样做
Select a.empid, a.name
from TableName as a
inner join TableName as b on a.Empid = b.Empid and a.idnumber = b.idnumber and b.badge like '3214%'
where a.badge like '6542%'