SUM(columnname)给出了与在SQL Server中手动求和列名不同的结果。为什么?

时间:2015-09-17 15:24:28

标签: mysql sql-server

为什么SUM(已售出)给出了与手动求和字段不同的结果?

如果我手动汇总已售出的字段,那么这个查询给了我正确的#:

SELECT     CustCode, FiscalYear, Sold 
FROM         DBNAME.dbo.SALESDETAIL
WHERE     (FiscalYear = YEAR({ fn NOW() }))
and CustCode = '248'
GROUP BY CustCode, FiscalYear, Sold

但是如果我尝试使用SUM函数,我的数量就会错误。任何人都可以帮助我吗?

SELECT     CustCode, FiscalYear, SUM(Sold) 
FROM         DBNAME.dbo.SALESDETAIL
WHERE     (FiscalYear = YEAR({ fn NOW() }))
and CustCode = '248'
GROUP BY CustCode, FiscalYear

目标是返回一个结果 - CustCode,FiscalYear和Sum(Sold)。感谢任何指针!

2 个答案:

答案 0 :(得分:2)

SELECT CustCode, FiscalYear, Sold 
FROM DBNAME.dbo.SALESDETAIL
WHERE (FiscalYear = YEAR({ fn NOW() }))
  AND CustCode = '248'
GROUP BY CustCode, FiscalYear, Sold;

相同
SELECT  DISTINCT CustCode, FiscalYear, Sold 
FROM DBNAME.dbo.SALESDETAIL
WHERE (FiscalYear = YEAR({ fn NOW() }))
  AND CustCode = '248';

基本上你可以摆脱多个Sold值。

尝试总结:

SELECT CustCode, FiscalYear, Sold 
FROM DBNAME.dbo.SALESDETAIL
WHERE (FiscalYear = YEAR({ fn NOW() }))
  AND CustCode = '248';

并与SUM(Sold)结果进行比较。

答案 1 :(得分:1)

第一个查询分组由CustCodeFiscalYearSold组成。即,每个这些字段的唯一组合返回一个行。这意味着如果您有相同CustCodeFiscalYear的多个条目具有相同的Sold,则您只会返回其中一行,并丢失重复项。因此,您的手动求和是缺少值,第二个查询不会错过。