我刚刚在sqlserver中使用adventureworks数据库。我陷入了疑问。 我想选择HumanResources.Employee的所有标题,这些标题是“男性”或“女性”,但不是两者。 即如果会计师是男性和女性,我想留下这个头衔。 我只需要那些性别为男性或女性的头衔。
我已经这样做了。
从humanresources.employee中选择distinct('title',其中gender ='M'
的distinct(title)
从humanresources.employee中选择distinct('F'
这两个查询之间的联接可能会起作用。但如果您有任何其他解决方案,请告诉我。
这不是作业。 :)
提前致谢。
答案 0 :(得分:2)
使用:
SELECT t.title
FROM HUMANRESOURCES.EMPLOYEE t
WHERE t.gender = 'M'
AND NOT EXISTS(SELECT NULL
FROM HUMANRESOURCES.EMPLOYEE e
WHERE e.gender = 'F'
AND e.title = t.title)
UNION ALL
SELECT t.title
FROM HUMANRESOURCES.EMPLOYEE t
WHERE t.gender = 'F'
AND NOT EXISTS(SELECT NULL
FROM HUMANRESOURCES.EMPLOYEE e
WHERE e.gender = 'M'
AND e.title = t.title)
答案 1 :(得分:1)
以下是更正后的版本
select title from HumanResources.Employee as t
where gender='M' And Not Exists(select null from HumanResources.Employee as e
where gender='F' And e.title =t.title)
Union
select title from HumanResources.Employee as t1
where gender='F' And Not Exists(select null from HumanResources.Employee as e1
where gender='M' And e1.title =t1.title)
order by title
答案 2 :(得分:0)
试试这个
select distinct title FROM humanResources.employee
WHERE gender = 'M' and
jobtitle not in (select title FROM humanResources.employee WHERE gender='F')
union
select distinct title FROM humanResources.employee
WHERE gender = 'F' and
jobtitle not in (select title FROM humanResources.employee WHERE gender='M')
答案 3 :(得分:0)
select title
from (
select distinct title, gender
from HumanResources.Employee) as temptable
group by title
having count(title) = 1
答案 4 :(得分:0)
为了多样化,我喜欢这个(仅仅是为了美学)
with WomensJobs as
(
select distinct(Title) title from HumanResources.Employee where Gender='F'
),
MensJobs as
(
select distinct(Title) title from HumanResources.Employee where Gender='M'
),
WomenOnlyJobs as
(
SELECT title from WomensJobs EXCEPT SELECT title from MensJobs
),
MenOnlyJobs as
(
SELECT title from MensJobs EXCEPT SELECT title from WomensJobs
)
select 'M', title from MenOnlyJobs
UNION
select 'F', title from WomenOnlyJobs
答案 5 :(得分:-1)
SELECT DISTINCT(title)
FROM HumanResources.Employee
WHERE t.gender = 'M'
EXCEPT
SELECT DISTINCT(t.title)
FROM HumanResources.Employee
WHERE t.gender = 'F'
UNION
SELECT DISTINCT(title)
FROM HumanResources.Employee
WHERE t.gender = 'F'
EXCEPT
SELECT DISTINCT(t.title)
FROM HumanResources.Employee
WHERE t.gender = 'M'