SQL Query用于计算具有基于另一列值的公共列值的行

时间:2018-02-11 18:09:18

标签: mysql sql

我有一个包含此数据的MySQL表:

CREATE TABLE job_history(
  id INT PRIMARY KEY AUTO_INCREMENT,
  employee VARCHAR(50),
  company VARCHAR(50)
);

INSERT INTO job_history(employee, company) VALUES
('John', 'IBM'),
('John', 'Walmart'),
('John', 'Uber'),
('Sharon', 'IBM'),
('Sharon', 'Uber'),
('Matt', 'Walmart'),
('Matt', 'Starbucks'),
('Carl', 'Home Depot');

SELECT * FROM job_history;
+----+----------+------------+
| id | employee | company    |
+----+----------+------------+
|  1 | John     | IBM        |
|  2 | John     | Walmart    |
|  3 | John     | Uber       |
|  4 | Sharon   | IBM        |
|  5 | Sharon   | Uber       |
|  6 | Matt     | Walmart    |
|  7 | Matt     | Starbucks  |
|  8 | Carl     | Home Depot |
+----+----------+------------+

Here's the corresponding SQL Fiddle

我想创建一个SQL查询来计算给定员工与桌面上其他员工之间的常见公司的数量。

例如,如果我想针对员工'John',我希望得到这样的结果:

  

Sharon:2
  马特:1   卡尔:0

由于Sharon与John(IBM和Uber)有两家共同的公司,Matt与John(沃尔玛)有一家共同的公司,而Carl与John共有0家公司。

我该怎么做?

5 个答案:

答案 0 :(得分:2)

首先,您需要一个left join - 因为您希望所有员工甚至是那些没有共同公司的员工。第二,group by得到计数:

select jh.employee, count(jh_john.company) as num_in_common
from job_history jh left join
     job_history jh_john
     on jh_john.company = jh.company and
        jh_john.employee = 'John'
where jh.employee <> 'John'
group by jh.employee;

注意:如果表格中可能存在重复项,请使用count(distinct)而不是count()

答案 1 :(得分:0)

试试这个:

SELECT jh2.employee, count(*)
FROM job_history jh1, job_history jh2
WHERE jh1.company = jh2.company
AND jh1.employee = 'John'
AND jh2.employee <> 'John'
GROUP BY jh2.employee

如果您希望它们从大多数公司的顺序到最少,请将其添加到查询的末尾:

ORDER BY count(*) DESC

答案 2 :(得分:0)

-- This will give the count with matching one

SELECT
employee, COUNT(company)
FROM job_history  WHERE company  IN
(
SELECT
company
FROM job_history  WHERE employee ='John' -- parameter
) AND employee <> 'John'  -- parameter
GROUP BY employee

-- Adding count with all employees  

SELECT DISTINCT 
ac.employee,
 COALESCE(mc.JobCount, 0)  AS JobCount
FROM job_history  AS ac LEFT OUTER JOIN
(
SELECT
employee, COUNT(company) AS JobCount
FROM job_history  WHERE company  IN
(
SELECT
company
FROM job_history  WHERE employee ='John'  -- parameter
) AND employee <> 'John'   -- parameter
GROUP BY employee
 ) AS mc ON mc.employee  = ac.employee
 WHERE ac.employee <> 'John'   -- parameter

答案 3 :(得分:0)

select 
    count(*) as comon_companies, b.employee 
from 
    job_history a
inner join  
    job_history b on a.company = b.company
where 
    a.employee <> b.employee
    and a.employee = 'sharon'
group by 
    b.employee

使用此查询获得所需的结果。您只需要在where子句中替换a.employee值以输入目标员工的姓名

答案 4 :(得分:0)

  

我该怎么做?

对不同员工和公司进行数据自我连接,然后将结果分组到员工并计算行数。

 SELECT B.employee, COUNT(A.company) FROM
 (SELECT  *  FROM JOB_HISTORY WHERE employee='John') A RIGHT JOIN
 (SELECT  *  FROM JOB_HISTORY WHERE employee<>'John') B
 ON A.company=B.company
 GROUP BY B.employee
 ORDER BY COUNT(A.company) DESC;