使用sum返回的值高出3倍时,结果是错误的

nvbavucw  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(379)
  1. ALTER PROCEDURE [dbo].[STOR_totalforadmin]
  2. AS
  3. BEGIN
  4. -- SET NOCOUNT ON added to prevent extra result sets from
  5. -- Interfering with SELECT statements.
  6. SET NOCOUNT ON;
  7. -- SELECT * FROM tblDraw
  8. SELECT tblretailer.ID,Name as retailername, tblretailer.AbcRate, tblretailer.AbRate,
  9. tblretailer.BoxRate, tblretailer.StraightRate,
  10. sum(isnull(ACount, 0)) as atotal ,
  11. sum(isnull(BCount, 0)) as Btotal,
  12. sum(isnull(CCount, 0)) as Ctotal,
  13. SUM(isnull(Count,0)) as strtotal,
  14. SUM(isnull(BoxCount,0)) as boxtotal,
  15. SUM(isnull(ABCount,0))as abtotal,
  16. SUM(isnull(ACCount,0))as actotal,
  17. SUM(isnull(BCCount,0)) as bctotal
  18. FROM tblretailer FULL JOIN Tbl_ABC abc ON (abc.RetailerID=tblretailer.ID)
  19. FULL JOIN TblDraw Draw ON (Draw.RetailerID=tblretailer.ID)
  20. FULL JOIN Tbl_ABACBC abbc ON (abbc.RetailerID=tblretailer.ID)
  21. GROUP BY Name, tblretailer.ID, tblretailer.AbcRate, tblretailer.AbRate, tblretailer.BoxRate, tblretailer.StraightRate
  22. END
xbp102n0

xbp102n01#

假设您有两个表,如下所示:

  1. declare @table1 table(Id int, Value int)
  2. declare @table2 table(Id int, Value int)

我们插入如下值:

  1. insert into @table1(Id, Value) values (1, 10)
  2. insert into @table1(Id, Value) values (2, 20)
  3. insert into @table1(Id, Value) values (3, 30)
  4. insert into @table2(Id, Value) values (1, 10)
  5. insert into @table2(Id, Value) values (1, 20)
  6. insert into @table2(Id, Value) values (2, 30)

首先,我们运行以下查询以获取摘要:

  1. select
  2. t1.Id,
  3. SUM(ISNULL(t1.Value, 0)) t1Sum,
  4. SUM(ISNULL(t2.Value, 0)) t2Sum
  5. from
  6. @table1 t1
  7. full join @table2 t2 on t1.id = t2.id
  8. group by
  9. t1.Id

结果:

  1. Id t1Sum t2Sum
  2. 1 20 30
  3. 2 20 30
  4. 3 30 0

表1中的id 1的和值为10,但为什么结果是20?
然后运行以下查询(无摘要和分组依据):

  1. select
  2. *
  3. from
  4. @table1 t1 full join @table2 t2 on t1.id = t2.id

结果:

  1. Id Value Id Value
  2. 1 10 1 10
  3. 1 10 1 20
  4. 2 20 2 30
  5. 3 30 NULL NULL

因为我们使用 full join ,用录制 Id = 1@table1 因为有两条记录 Id = 1 在@表2中。

展开查看全部
iezvtpos

iezvtpos2#

将总和除以3,如下所示:

  1. sum(isnull(ACount, 0))/3

为了所有人。

相关问题