减法操作返回错误结果

时间:2014-06-18 08:58:09

标签: sql sql-server

SELECT 
    TOB.SchoolID,
    SUM (TOB.Rice)- SUM(TDMD.Rice)
FROM  tblOpeningBalance TOB 
JOIN  tblDailyMidDayDetails TDMD 
    ON TOB.SchoolID = TDMD.SchoolID
WHERE  TOB.Date<=CONVERT(datetime,'19/06/2014',103) 
GROUP BY TOB.SchoolID;

这是我得错结果的查询。

要获取我想单独减去的值,查询是..

SELECT 
    DISTINCT SchoolID, 
    SUM (Rice) AS Rice
FROM  tblOpeningBalance 
WHERE  Date <= CONVERT(datetime,'19/06/2014',103) 
GROUP BY SchoolID;

第二次查询:

SELECT 
    SchoolID,
    SUM(Rice) AS Rice 
FROM tblDailyMidDayDetails 
WHERE Date<=CONVERT(datetime,'19/06/2014',103)
GROUP BY SchoolID;

这两个查询返回真实结果,但在尝试通过加入获取减去的结果时,我得到了错误的值。

可能是因为误解我做错了。

请指导我!

2 个答案:

答案 0 :(得分:2)

只需将现有查询(DISTINCT除外)保留为子查询:

SELECT ob.SchoolID,
       ob.Rice - dmdd.Rice
FROM (
  Select SchoolID, 
  SUM (Rice) AS Rice
  FROM tblOpeningBalance 
  Where 
  Date<='20140619' 
  GROUP BY SchoolID) ob
     INNER JOIN
(
  SELECT SchoolID,SUM(Rice) AS Rice
  FROM tblDailyMidDayDetails
  WHERE Date<='20140619' 
GROUP BY SchoolID) dmdd
     ON
         ob.SchoolID = dmdd.SchoolID

这可确保联接每一侧的每个SchoolID只有一行,这样可以避免在聚合之前复制某些值。

我猜你的问题是因为两个表中的同一SchoolID目前有多行。你得到的问题在这里说明。假设表1有数据:

SchoolID    Column1     Rice
1           abc         10
1           def         20

表2中有数据:

SchoolID    Column2     Rice
1           ghi         30
1           jkl         40

在计算聚合之前执行连接的结果是创建以下行:

SchoolID    Column1     Rice    SchoolID     Column2     Rice
1           abc         10      1            ghi         30
1           abc         10      1            jkl         40
1           def         20      1            ghi         30
1           jkl         20      1            jkl         40

希望你能看出为什么针对这个结果集的计算聚合会产生错误的结果。

答案 1 :(得分:1)

我们也可以这样使用CTE ..

;WITH CTE AS  
    (Select SchoolID As SchoolID, 
  SUM (Rice) AS Rice
  FROM tblOpeningBalance 
  Where 
  Date<='20140619' 
  GROUP BY SchoolID)
,CTE2 AS 
  ( SELECT SchoolID As SchoolID,SUM(Rice) AS Rice
  FROM tblDailyMidDayDetails
  WHERE Date<='20140619' 
    GROUP BY SchoolID)

Select C.SchoolID,C.Rice - CC.Rice As RIce
     FROM CTE C
INNER JOIN CTE2 CC
    ON c.SchoolID = Cc.SchoolID
GROUP BY C.SchoolID