2011-11-25 165 views
0

我已經嘗試了很多數字如何從兩個表中對於獲得計數主表如何獲取SQL Server中的計數?

我有三個表

enter image description here

使用我需要得到這個輸出這些表中的值。 。

enter image description here

嘗試,但能得到期望的結果 http://en.wikipedia.org/wiki/Join_(SQL) SQL - LEFT OUTER JOIN and WHERE clause http://forums.devshed.com/oracle-development-96/combination-of-left-outer-join-and-where-clause-383248.html

+0

試圖左外連接,右外連接,內連接,... – AnandMohanAwasthi

+2

_show_我們你試過了什麼。 –

+0

我正在嘗試給定的解決方案,請給我一點時間來標記正確答案並投票。什麼讓你們降級? – AnandMohanAwasthi

回答

4

你必須首先GROUP BY子查詢,然後JOIN主表:

SELECT 
    a.AttributeId  
    , COALECSE(cntE, 0) AS cntE 
    , COALECSE(cntM, 0) AS cntM 
FROM 
    AttributeMaster AS a 
    LEFT JOIN 
    (SELECT 
      AttributeId 
     , COUNT(*) AS cntE 
     FROM 
      EmployeeMaster 
     GROUP BY 
      AttributeId 
    ) em 
     ON em.AttributeId = a.AttributeId 
    LEFT JOIN 
    (SELECT 
      AttributeId 
     , COUNT(*) AS cntM 
     FROM 
      MonthlyDerivedMaster 
     GROUP BY 
      AttributeId 
    ) mdm 
     ON mdm.AttributeId = a.AttributeId 
+0

感謝您的解決方案,這是殺我..非常感謝.. – AnandMohanAwasthi

0
SELECT AttributeId, 
(SELECT COUNT(Eid) FROM EmployeeMaster WHERE AttributeMaster.AttributeId = EmployeeMaster.AttributeId) as master_eid, 
(SELECT COUNT(Eid) FROM MonthnlyDerivedMaster WHERE AttributeMaster.AttributeId = MonthnlyDerivedMaster.AttributeId) as monthly_eid 
FROM AttributeMaster 
相關問題