简体   繁体   中英

Get all records having count from one table is greater than sum of other table

I have three tables 1) CustomerOrders , 2) StockItems and 3) OrderContentsLine . StockItems have customerorderid (one to many relationship with CustomerOrders ) and OrderContentsLine contains order items with item quantity (obviously one to many relationship with CustomerOrders ).

Now I want to get All orders which have sum of quantity from OrderContentsLine table greater than count of StockItems

myquery looks like this

select co.OrderNumber,si.SalesOrderID, sum(ocl.Quantity) Ordered, count(si.SalesOrderID) Allocated from CustomerOrders co
inner join StockItems si on co.OrderID = si.SalesOrderID
inner join OrderContentsLine ocl on ocl.OrderID=co.OrderID
where co.CompanyId=531
group by si.SalesOrderID,co.OrderNumber
having count(si.SalesOrderID)>sum(ocl.Quantity)

but this query shows no results, and I am damn sure that many orders have greater order conterntline items than sum of quantity from StockItems table.

Can you please review my query and suggest the better way to get these orders!

My required output is

在此处输入图像描述

NOTE: this output is not generated by query !

I have just created a query that gives me the required output

select * from(
select co.OrderNumber, co.OrderID, co.OrderStatus,
(select sum(tbl.Quantity) from OrderContentsLine tbl where tbl.OrderID=co.OrderID) Ordered, 
(select count(*) from StockItems tbl2 where tbl2.SalesOrderID=co.OrderID ) Allocated 
from CustomerOrders co
)temp where temp.Allocated> temp.Ordered

Your problem is the multiple one-to-many joins. You are counting and summing duplicates. For example, if you have 1 order with 2 stock items, and 3 order lines, your join of the three tables will have 6 rows. You have no relationship between StockItem and OrderContentsLine, so you get a cartesian product.

You probably want something like

WITH ord AS 
(
    SELECT co.CompanyId, co.OrderID, co.OrderNumber, SUM(ocl.Quantity) AS Ordered
    FROM CustomerOrders co
    INNER JOIN OrderContentsLine ocl ON ocl.OrderID = co.OrderID
    GROUP BY co.CompanyId, co.OrderNumber
), al AS
(
    SELECT co.CompanyId, co.OrderID, co.OrderNumber, COUNT(si.SalesOrderID) AS Allocated
    FROM CustomerOrders co
    INNER JOIN StockItems si ON co.OrderID = si.SalesOrderID
    GROUP BY co.CompanyId, co.OrderNumber
)
SELECT ord.CompanyId, ord.OrderNumber, ord.Ordered, al.Allocated
FROM ord 
INNER JOIN al ON ord.OrderID = al.OrderID
WHERE companyId = 531
AND al.Allocated > ord.Ordered

Obviously hard to test with no data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM