SQL查找多个值难度

时间:2015-01-23 13:37:59

标签: sql sql-server

我正在尝试为项目生成正确的SQL。

以下是一个示例数据集:

DateTime          |  EmpID |  Function  |  Location
--------------------------------------------------
1/23/2015 2:00PM  |  123   |  1         |  1
1/23/2015 2:10PM  |  123   |  2         |  1
1/23/2015 2:20PM  |  123   |  1         |  2
1/23/2015 2:40PM  |  123   |  2         |  2
1/24/2015 2:00PM  |  321   |  1         |  2
1/24/2015 2:15PM  |  321   |  2         |  2
1/24/2015 2:30PM  |  321   |  1         |  3

我需要提取所有记录的计数,其中functionid = 1且位置必须等于1和2.因此第一行和第三行将被返回并被视为1的计数。

希望我对此有所了解。基本上我需要知道一个员工在两个地方的次数。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:0)

按EmpId分组并计算位置。

SELECT *
  FROM MyTable T1 
 WHERE Function = 1 AND
       NOT EXISTS (SELECT 1 
                     FROM MyTable T2 
                    WHERE T1.EmpId = T2.EmpId AND
                          T1.Function = T2.Function AND
                          T2.Location NOT IN (1, 2))
GROUP BY EmpId
HAVING Count(DISTINCT Location) > 1

答案 1 :(得分:0)

SELECT EmpID , COUNT(*) total, COUNT (CASE WHEN Location = 1 THEN 1 END) was_in_1,COUNT (CASE WHEN Location = 2 THEN 1 END) was_in_2
FROM table
WHERE Function = 1
GROUP BY EmpID
HAVING MAX(CASE WHEN Location = 1 THEN 1 ELSE 0 END) = MAX(CASE WHEN Location = 2 THEN 1 ELSE 0 END)

但如果您想知道该员工是否在任何2个地点,那么jarlh会给出正确的评论

group by EmpID
having count(distinct location) >= 2

答案 2 :(得分:0)

SELECT A.EmpID, COUNT(*) 
FROM YOURTABLENAME A 
INNER JOIN YOURTABLENAME B 
ON A.EmpID= B.EmpID
WHERE  A.Location = 1 and B.Location = 2 
and A.Function = B.Function and A.Function = 1
GROUP BY A.EmpID

答案 3 :(得分:0)

没有测试过,但认为这样可行

SELECT EmpID, COUNT(EmpID) AS NumOfTimes
From [Table Name] 
WHERE FunctionID = 1 AND (Location = 1 OR Location = 2)
GROUP BY EmpID 
HAVING NumOfTimes = 2