如何组合 group by、where 和逻辑运算符?

How to combine group by, where and logical operators?

我有如下数据结构

| Name  | Contract Type |
|:------|--------------:|
| Frank | Student       |
| Frank | Staff         |
| Frank | Staff         |
| John  | Internship    |
| John  | Student       |
| John  | Staff         |
| Tim   | Internship    |
| Tim   | Staff         |

我想获得 Names 有过学生合同和历史上另一份合同的员工。我的方法是

Select Name, count(Name) from table
where ContractType = ('Student') AND (ContractType = ('Staff') OR ContractType = ('Internship') )     
group by Name having count (Name) > 1

这里的问题是我仍然得到所有员工。谁能帮我完成这个?

Name 分组,只取至少有一次学生合同且合同总数超过 1 份的组

Select Name
from your_table
group by Name 
having sum(case when ContractType = 'Student' then 1 else 0 end) > 0
   and count(distinct ContractType) > 1

使用GROUP BY:

SELECT Name
FROM dbo.YourTable
GROUP BY Name
HAVING SUM(CASE WHEN [Contract Type] = 'Student' THEN 1 ELSE 0 END) >= 1
AND SUM(CASE WHEN [Contract Type] <> 'Student' THEN 1 ELSE 0 END) >= 1;

但是你也可以使用EXISTS:

SELECT DISTINCT A.Name
FROM dbo.YourTable A
WHERE EXISTS(SELECT 1 FROM dbo.YourTable
             WHERE Name = A.Name
             AND [Contract Type] = 'Student')
AND EXISTS( SELECT 1 FROM dbo.YourTable
            WHERE Name = A.Name
            AND [Contract Type] <> 'Student');

您也可以使用 GROUP BY 然后 IN:

SELECT name
FROM table
GROUP BY name
HAVING COUNT(*) > 1
AND name IN
(SELECT name
 FROM table
 WHERE contracttype = 'student')

此处测试:http://sqlfiddle.com/#!9/38fa36/1