求更好的sql解决办法
上次去一家公司面试,其中有一道sql语句的题目,题目如下:
有一张含有ID,name,city三个字段的表,表中存储的是某公司员工外派常驻城市信息,每个人的常驻城市可能有多个,现在请用一条sql语句查询出常驻城市与张三完全相同的人员列表。如果数据如下表,那么最后得出的结果应该是马六
当时没有多想,使用了比较笨的方法写了出来,如下
select name from (
select * from UC uc1
where city in ( select city from UC uc2 where uc2. name =' 张三 ')
and city not in ( select city from UC uc3 where uc3 .city not in ( select city from UC uc4where uc4. name =' 张三 '))
and uc1 . name <> ' 张三 '
) tmp
group by name
having COUNT ( city) = ( select COUNT (city ) from UC where name = '张三 ' )
;with t as(
SELECT name, value = stuff((SELECT ',' + city
FROM #TABLE1 AS t
WHERE t .name = #TABLE1.name FOR xml path('')), 1, 1, '')
FROM #TABLE1
GROUP BY name
)
select name from t where name<>'张三'
and value=(select value from t where name='张三')