我在SQL Server中的两个日期之间总结价格列时遇到问题。
我有这样的查询:
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)上添加了SUM作为Achiev"像这样:
CAST(sum(OINV.DocTotal) as float) as Achiev
但是,它返回了错误的结果:
日期上的Achiev列的正确结果应为 4906230
非常感谢您的帮助!
更新(已解决) 我已经解决了这个问题。它只是为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
感谢所有帮助过我的人!
答案 0 :(得分:4)
问题是与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
答案 1 :(得分:1)
如果你想显示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'
如果你想显示每个海洋男人的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