我有这个查询,它计算我每月收到的退货发票数量:
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我会把它放在某个地方(必须是一个总和,因为一张发票可以有很多项):
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发布于 2017-05-15 23:25:14
您只需要考虑存在超过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);发布于 2017-05-15 22:41:54
您希望筛选包含超过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)https://stackoverflow.com/questions/43982246
复制相似问题