我有这个查询,它计算我每月的退货发票金额:
SELECT MONTH(ORIN.DocDate) mes, COUNT(*) tot
FROM ORIN
WHERE DATEDIFF(MONTH, ORIN.DocDate, GETDATE()) <= 12
GROUP BY MONTH(ORIN.DocDate)
现在我只需要获得物品数量超过100的发票。为此,我必须加入另一张表(发票项目):
INNER JOIN RIN1 ON ORIN.DocEntry = RIN1.DocEntry
在某个地方,我会把它(必须是SUM,因为一张发票可以有很多项目):
WHERE SUM(RIN1.Quantity) > 100
问题是我不知道如何进行此查询。我的最后一次尝试如下,但它没有带来正确的价值观:
SELECT MONTH(ORIN.DocDate) mes, COUNT(*) tot
FROM ORIN
INNER JOIN RIN1 ON ORIN.DocEntry = RIN1.DocEntry
WHERE DATEDIFF(MONTH, ORIN.DocDate, GETDATE()) <= 12
GROUP BY MONTH(ORIN.DocDate)
HAVING SUM(RIN1.Quantity) > 100
答案 0 :(得分:1)
您只想考虑超过100件商品的发票。两种方法:
1)使用相关子查询计算项目:
select month(docdate) mes, count(*) tot
from orin
where datediff(month, docdate, getdate()) <= 12
and
(
select sum(quantity)
from rin1
where rin1.docentry = orin.docentry
) > 100
group by month(docdate);
2)查找超过100件物品的发票清单:
select month(docdate) mes, count(*) tot
from orin
where datediff(month, docdate, getdate()) <= 12
and docentry in
(
select docentry
from rin1
group by docentry
having sum(quantity) > 100
)
group by month(docdate);
答案 1 :(得分:0)
您希望过滤包含超过100件商品的发票,如RIN1.Quantity
所示。
只需在WHERE
:
SELECT MONTH(ORIN.DocDate) mes, COUNT(*) tot
FROM ORIN
INNER JOIN RIN1 ON ORIN.DocEntry = RIN1.DocEntry
WHERE DATEDIFF(MONTH, ORIN.DocDate, GETDATE()) <= 12
AND RIN1.Quantity > 100
GROUP BY MONTH(ORIN.DocDate)