empid projectId TaskID
100 500 1
100 501 1
100 502 1
101 500 2
101 500 5
101 500 1
102 400 1
103 300 2
104 300 2
105 300 2
我试图根据项目ID列出仅在多个项目上工作的员工。 我试过了distinct和GROUP BY。但我无法准确地理解它。
从上表中的我期待像这样的结果
empid projectId
100 500
100 501
100 502
答案 0 :(得分:6)
试试这个(修订后的代码)
SELECT DISTINCT EmpId, ProjectId
FROM TableX
WHERE EmpId IN
(
SELECT EmpId
FROM TableX
GROUP BY EmpId
HAVING COUNT (DISTINCT ProjectId) > 1
)
这应该给你
EmpId ProjectId
----------- -----------
100 500
100 501
100 502
3 row(s)
修改在评论
中为OP附加问题添加的内容给你一个计数的计数ProjectIds意味着GROUP BY将处于EmpId
级别并且不需要子查询
SELECT EmpId, Count (Distinct ProjectId) Projects
FROM TableX
GROUP BY EmpId
要为具有多个项目的所有员工计算项目数,请执行以下操作
SELECT EmpId, Count (Distinct ProjectId) Projects
FROM TableX
GROUP BY EmpId
Having Count (Distinct ProjectId) > 1
答案 1 :(得分:1)
您还可以使用窗口COUNT()
:
WITH counted AS (
SELECT
empid,
projectId,
COUNT(DISTINCT projectId) OVER (PARTITION BY empid) AS ProjectCount
FROM atable
)
SELECT DISTINCT
empid,
projectId
FROM counted
WHERE ProjectCount > 1
参考文献:
答案 2 :(得分:0)
SELECT y.empid, y.projectId
FROM (SELECT empid
FROM YourTable
GROUP BY empid
HAVING COUNT(*) > 1) t
INNER JOIN YourTable y
ON t.empid = y.empid
ORDER BY y.empid, y.projectId