2013-05-21 55 views
0

我需要編寫一個查詢以返回公司的名稱以及公司擁有的特定工作訂單的數量。計算每家公司的工作訂單數量

現在我的查詢是這樣的:

SELECT c.name, cj.joborder_id 
FROM company c, joborder jo, candidate_joborder cj 
WHERE c.company_id=jo.company_id 
AND jo.joborder_id=cj.joborder_id 
AND jo.status = 'Active' 
AND cj.status=700; 

這將返回如下表:

Name | Job Order ID 
X | 1874 
Y | 2003 
Y | 2003 
Z | 2001 

我要的是:

Name | Count 
X | 1 
Y | 2 
Z | 1 

有人可以幫助我?

感謝

回答

2

您想查詢如下:

SELECT c.name, 
     count(cj.joborder_id) 
FROM company c, 
    joborder jo, 
    candidate_joborder cj 
WHERE c.company_id=jo.company_id 
    AND jo.joborder_id=cj.joborder_id 
    AND jo.status = 'Active' 
    AND cj.status=700 
GROUP BY c.name; 

我建議對SQL聚集和以下引用專門小組和計數:

+0

感謝。我將用它們作爲未來的參考。 – Jail

2

使用COUNT()GROUP BY條款,

SELECT c.name, COUNT(cj.joborder_id) TotalCount 
FROM company c, joborder jo, candidate_joborder cj 
WHERE c.company_id=jo.company_id 
     AND jo.joborder_id=cj.joborder_id 
     AND jo.status = 'Active' 
     AND cj.status=700 
GROUP BY c.name 

使用ANSI JOIN

SELECT c.name, 
     COUNT(cj.joborder_id) TotalCount 
FROM company c 
     INNER JOIN joborder jo 
      ON c.company_id = jo.company_id 
     INNER JOIN candidate_joborder cj 
      ON jo.joborder_id = cj.joborder_id 
WHERE jo.status = 'Active' AND 
     cj.status=700 
GROUP BY c.name 
1
SELECT DISTINCT(c.name), COUNT(cj.joborder_id) 
FROM company c, joborder jo, candidate_joborder cj 
WHERE c.company_id=jo.company_id 
AND jo.joborder_id=cj.joborder_id 
AND jo.status = 'Active' 
AND cj.status=700 
GROUP BY c.name 
+0

當您使用group by時,不需要使用distinct。 –

+1

是的,並非嚴格需要。如果你有'c.name'上的索引,那就沒有關係了。如果沒有,你會期望'DISTINCT(c.name)'表現更好。 – Ryan