如何组合group by,where和logical运算符?

时间:2016-09-20 15:25:16

标签: sql tsql group-by where

我有以下数据结构

| 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

这里的问题是我仍然得到所有员工。有谁可以帮助我完成这项工作?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

使用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');

答案 2 :(得分:2)

您还可以使用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