如何将来自不同表的记录组合成一个带计数的记录集

时间:2015-08-27 03:12:40

标签: sql sql-server-2008-r2

我有以下代码

SELECT 
    dbo.tbl1.RecId, dbo.tbl1.CertType, 
    COUNT(dbo.tbl2.CertType) AS   Quantity
FROM 
    dbo.tbl3 
INNER JOIN
    dbo.tbl2 ON dbo.tbl3.RequestNo = dbo.tbl2.RequestNo 
RIGHT OUTER JOIN
    dbo.tbl1 ON dbo.tbl2.CertType = dbo.tbl1.RecId
GROUP BY 
    dbo.tbl1.RecId, dbo.tbl1.CertType

并返回此结果:

RecId CertType   Quantity
1     Clearance         4
2     Permit            0

它只计算来自tbl3的数量,但我希望它也会计算来自tbl4的记录,但只是不知道如何为其添加代码。

注意:tbl4tlb3的格式相同。谢谢你的帮助。

我希望结果如下:

RecId CertType   Quantity
1     Clearance         4
2     Permit            2

1 个答案:

答案 0 :(得分:0)

我认为这个解决方案对我有用。

SELECT   dbo.tbl1.RecId, dbo.tbl1.CertType, 
COUNT(dbo.tbl2.RequestNo)  AS   Quantity
FROM         dbo.tbl3 INNER JOIN 
         dbo.tbl2 ON dbo.tbl3.RequestNo = dbo.tbl2.RequestNo
         RIGHT OUTER JOIN
         dbo.tbl1 ON dbo.tbl2.CertType = dbo.tblBasicPermitFeeSchedule.RecId                                          

 GROUP BY dbo.tbl1.RecId, dbo.tbl1.CertType

UNION
SELECT   dbo.tbl1.RecId, dbo.tbl1.CertType, 
COUNT(dbo.tbl2.RequestNo)  AS   Quantity
FROM         dbo.tbl4 INNER JOIN 
         dbo.tbl2 ON dbo.tbl4.RequestNo = dbo.tblRequests.RequestNo
         RIGHT OUTER JOIN
         dbo.tbl1 ON dbo.tbl2.CertType = dbo.tbl1.RecId                                          

 GROUP BY dbo.tbl1.RecId, dbo.tbl1.CertType

感谢您的所有想法。