SQL 两个日期之间的总和列

SQL Sum Column Between Two Dates

我无法对 SQL 服务器中两个日期之间的价格列求和。

我有这样的查询:

SELECT
    OSLP.SlpName as Salesman,
    CAST(OINV.DocTotal as float) as Achiev,
    OINV.TaxDate
FROM 
    OINV
INNER JOIN 
    INV1 ON INV1.DocEntry = OINV.DocEntry
INNER JOIN 
    OSLP ON OINV.SlpCode = OSLP.SlpCode
INNER JOIN 
    OITM ON INV1.ItemCode = OITM.ItemCode
INNER JOIN 
    OMRC ON OITM.FirmCode = OMRC.FirmCode
INNER JOIN 
    OCRD ON OINV.CardCode = OCRD.CardCode
WHERE
    OSLP.SlpName LIKE '01-2 Ika' 
    AND OINV.TaxDate BETWEEN '20160804' AND '20160806'
GROUP BY
    OSLP.SlpName, OINV.DocTotal, OINV.TaxDate

上面的查询结果是这样的:

我还在 "CAST(OINV.DocTotal as float) as Achiev" 上添加了 SUM,如下所示:

CAST(sum(OINV.DocTotal) as float) as Achiev

但是,它 returns 错误的结果:

日期上 Achiev 列的正确结果应该是 4906230

非常感谢您的帮助!

更新(已解决) 我已经解决了这个问题。它只是将 distinct 添加到 SUM 查询中,因为我的查询中有重复的数据。

查询:

SELECT
  OSLP.SlpName as Salesman,
  sum(CAST(INV1.Quantity as float)) as Qty,
  sum(DISTINCT CAST(OINV.DocTotal as float)) as Achiev
FROM 
  OINV
INNER JOIN 
  INV1 ON INV1.DocEntry = OINV.DocEntry
INNER JOIN 
  OSLP ON OINV.SlpCode = OSLP.SlpCode
INNER JOIN 
  OITM ON INV1.ItemCode = OITM.ItemCode
INNER JOIN 
  OMRC ON OITM.FirmCode = OMRC.FirmCode
INNER JOIN 
  OCRD ON OINV.CardCode = OCRD.CardCode
WHERE
  OSLP.SlpName LIKE '01-2 Ika' 
  AND OINV.TaxDate BETWEEN '20160804' AND '20160806'
GROUP BY
  OSLP.SlpName

它 returns :

感谢所有帮助过我的人!

问题出在 group by .. 从 group by 中删除 OINV.DocTotal 并像下面那样求和

SELECT
OSLP.SlpName as Salesman,
sum(CAST(OINV.DocTotal as float)) as Achiev,
OINV.TaxDate
FROM OINV
  INNER JOIN INV1 ON INV1.DocEntry = OINV.DocEntry
  INNER JOIN OSLP ON OINV.SlpCode = OSLP.SlpCode
  INNER JOIN OITM ON INV1.ItemCode = OITM.ItemCode
  INNER JOIN OMRC ON OITM.FirmCode = OMRC.FirmCode
  INNER JOIN OCRD ON OINV.CardCode = OCRD.CardCode
WHERE
OSLP.SlpName like '01-2 Ika' And OINV.TaxDate between '20160804' and '20160806'
GROUP BY
  OSLP.SlpName,
  OINV.TaxDate

如果您想显示每个 seales 人的 DocTotal 总和,并且还想按 TaxDate 拆分它, 使用以下脚本

SELECT
OSLP.SlpName as Salesman,
CAST(sum(OINV.DocTotal) OVER(PArtition by OSLP.SlpName Order by   OINV.TaxDate) as float) as Achiev
OINV.TaxDate
FROM OINV
  INNER JOIN INV1 ON INV1.DocEntry = OINV.DocEntry
  INNER JOIN OSLP ON OINV.SlpCode = OSLP.SlpCode
  INNER JOIN OITM ON INV1.ItemCode = OITM.ItemCode
  INNER JOIN OMRC ON OITM.FirmCode = OMRC.FirmCode
  INNER JOIN OCRD ON OINV.CardCode = OCRD.CardCode
WHERE
OSLP.SlpName like '01-2 Ika' And OINV.TaxDate between '20160804' and '20160806'

如果您想显示每个 seales 人的 DocTotal 总和 使用以下脚本。

SELECT
OSLP.SlpName as Salesman,
CAST(sum(OINV.DocTotal) as float) as Achiev
FROM OINV
  INNER JOIN INV1 ON INV1.DocEntry = OINV.DocEntry
  INNER JOIN OSLP ON OINV.SlpCode = OSLP.SlpCode
  INNER JOIN OITM ON INV1.ItemCode = OITM.ItemCode
  INNER JOIN OMRC ON OITM.FirmCode = OMRC.FirmCode
  INNER JOIN OCRD ON OINV.CardCode = OCRD.CardCode
WHERE
OSLP.SlpName like '01-2 Ika' And OINV.TaxDate between '20160804' and '20160806'
GROUP BY OSLP.SlpName