如何从来自另一个查询的记录中减去来自一个查询的记录?

时间:2012-09-25 05:03:38

标签: sql-server

这两个查询,返回多个记录,那么有没有解决方法从另一个结果中减去一个结果的每一行数据?

QUERY1:

SELECT COUNT(*) As AbhidayNotPaidSansthan
 FROM PanjikaranMaster GROUP BY Zila

QUERY2:

SELECT COUNT(*) as anps FROM AbhidayMaster,PanjikaranMaster
    WHERE PanjikaranMaster.OfficeRegId=AbhidayMaster.OfficeRegId AND
    AbhidayMaster.DipositDate Between ('2012-09-19') AND ('2012-09-24')
GROUP BY PanjikaranMaster.Zila

1 个答案:

答案 0 :(得分:2)

尝试使用此查询,它将解决您的问题:

SELECT ISNULL(a.cnt,0) -  ISNULL(b.cnt,0) AS CNT,a.Zila
FROM
    (SELECT Zila,COUNT(*) as cnt As AbhidayNotPaidSansthan
    FROM PanjikaranMaster GROUP BY Zila) a
    LEFT JOIN 
    (SELECT Zila,COUNT(*) as cnt FROM AbhidayMaster,PanjikaranMaster
    WHERE PanjikaranMaster.OfficeRegId=AbhidayMaster.OfficeRegId AND
    AbhidayMaster.DipositDate Between ('2012-09-19') AND ('2012-09-24')
    GROUP BY PanjikaranMaster.Zila) b 
    ON a.Zila = b.Zila

我在 SQLFIDDLE

中进行了类似的测试