I am running a query on two tables that needs to return the total number of lines in each sales order and a total of the items ordered.
A simplified version of the SalesOrder
table is constructed like this:
SalesOrderID | Customer | SODate |
---|---|---|
102 | Bob Smith | 12/15/2021 |
101 | Jane Doe | 12/05/2021 |
100 | Sarah Joy | 12/01/2021 |
The second table, SalesOrderLine
, contains the line items in the sales order:
SalesOrderID | LineNumber | Item | Quantity |
---|---|---|---|
100 | 1 | Nuts | 5 |
100 | 2 | Bolts | 10 |
100 | 3 | Washers | 3 |
101 | 1 | Screws | 15 |
102 | 1 | Nails | 25 |
102 | 2 | Hooks | 5 |
The result of the query would look like this:
SalesOrderID | SODate | Customer | TotalLines | TotalItems |
---|---|---|---|---|
102 | 12/15/2021 | Bob Smith | 2 | 30 |
101 | 12/05/2021 | Jane Doe | 1 | 15 |
100 | 12/01/2021 | Sarah Joy | 3 | 18 |
I am locking up on how to use the query to return the Total Number of Lines and Total Number of Items per SalesOrderID.
SELECT SalesOrder.SalesOrderID, SalesOrder.SODate, SalesOrder.SOCustomer
?? Total Number of Lines and Total Number of Items ??
FROM SalesOrder
INNER JOIN SalesOrders ON SalesOrder.SalesOrderID = SalesOrderLine.SalesOrderID
ORDER BY SalesOrderID
CodePudding user response:
You can use apply
:
select so.*, soo.*
from salesorder so cross apply
( select count(*) as Totallines, sum(soo.quantity) as TotalQty
from SalesOrders soo
where soo.SalesOrderID = so.SalesOrderID
) soo;
CodePudding user response:
You are almost done, except the aggregation.
Query
select so.SalesOrderID, so.SODate, so.SOCustomer,
count(sol.LineNumber) as TotalLines, sum(sol.Quantity) as TotalItems
from SalesOrder as so
join SalesOrderLine as sol
on so.SalesOrderID = sol.SalesOrderID
group by so.SalesOrderID, so.SODate, so.SOCustomer
order by SalesOrderID;