根据第三列的计数计算不同的列

时间:2014-05-02 20:55:10

标签: mysql sql database multidimensional-array

我的查询:

SELECT DISTINCT job_id, cust_id, a.skill_id FROM aaa.jp_job_skill_ref a INNER JOIN aaa.jp_cust_skill_ref b ON a.skill_id = b.skill_id ORDER BY `job_id`, `cust_id`, `skill_id`;

返回3列数据。但是,这两个表都是具有数百个相同cust_id和skill_id或job_id和skill_id的引用表,因此具有按job_id和cust_id分组的计数(a.skill_id)将返回skill_id计数为30 +

 job_id, cust_id, skill_id
     2,       1,        1
     2,       1,        2
     2,       1,        9
     2,       3,        1
     2,       3,        2
     2,       3,        9
     2,       3,       10
     2,       4,        1
     2,       4,        9
     3,       1,       12
     3,       3,       10
     3,       4,       12

我希望它返回的是作业ID,Cust ID和不同Skill_ID的计数。返回以下数据集我缺少什么:?

job_id, cust_id, skill_id
'2',   '1',     '3'
'2',   '3',     '4'
'2',   '4',     '2'
'3',   '1',     '1'
'3',   '3',     '1'
'3',   '4',     '1'

4 个答案:

答案 0 :(得分:2)

您需要group by

SELECT job_id, cust_id, count(distinct a.skill_id)
FROM aaa.jp_job_skill_ref a INNER JOIN
     aaa.jp_cust_skill_ref b
     ON a.skill_id = b.skill_id
GROUP BY `job_id`, `cust_id`;

这是一个非常基本的SQL查询。 group by是SQL语言的重要组成部分。您应该研究它,以便使用SQL。

答案 1 :(得分:2)

你在找这个吗?

select 
j1.job_id,
j1.cust_id,
j2.cnt as skill_id
from jp_job_skill_ref j1
inner join (
  select 
  job_id,
  cust_id,
  count(skill_id) as `cnt`
  from jp_job_skill_ref 
  group by job_id,cust_id

)j2
on j1.job_id = j2.job_id AND j1.cust_id = j2.cust_id
group by j1.job_id,j1.cust_id;

如果您需要不同的skill_id计数,请更换

count(skill_id) as `cnt`

count(distinct skill_id) as `cnt` 

<强> DEMO

我已将示例中的表名aaa.jp_job_skill_ref替换为jp_job_skill_ref

答案 2 :(得分:1)

SELECT 2 job_id, 1 cust_id, 3 skill_id
UNION
SELECT 2,3,4
UNION
SELECT 2,4,2
UNION
SELECT 3,1,1
UNION
SELECT 3,3,1
UNION
SELECT 3,4,1;

答案 3 :(得分:1)

SELECT DISTINCT CONCAT(job_id, cust_id), a.skill_id 
FROM aaa.jp_job_skill_ref a 
INNER JOIN aaa.jp_cust_skill_ref b 
ON a.skill_id = b.skill_id 
ORDER BY `job_id`, `cust_id`, `skill_id`;