How do i Calculate Fill Order Rate Using Sales Order Line Item - sql

We are trying to write a query to find out how much of the order was fullfilled in the first invoice on that order. Look at ArTrnInvoice table for Invoice info and OrderDetail for orders info. Compare qty ordered on each sales order line to what was fulfilled on the first invoice on that order
We tried
select case when SalesOrderLine>0 THEN QtyInvoiced /MOrderQty *100 Else End as Order_fILL_RATE FROM OrderDetail a Left JOIN
OrderHeader b ON a.SalesOrder = b.SalesOrder
WHERE b.Order Status ='9'
Basically,Trying to Output :
How much of the order was fullfilled in the first invoice - Let' say I ordered 2000$ worth of items. And Business Org invoiced this to me in two parts. First 1800$ within 10 days and then another 200$ later (or didn't ship this at all). In this case fill rate = 90%
Given Conditions
We have sql server 2012. Trying to calculate Fill Order Rate Using Order Line Item.
We have 3 table which consist of OrderHeader Info,OrderDetail Info, Invoice info table .
Structure of these tables are Here in link:
OrderDetail Table
Structure is
OrderHeader Table DDL
Also OrderStatus='9' means Fulfilled Order.
Any help on it would be much appreciated ?

Related

Get the product of two values from two different tables

If anyone can help me figure out where I am going wrong with this SQL that would be great. Please see my attempt to answer it below. I have answer how I think it should be answered but I am very confused by the exam advice below, which says I should use a SUM function? I have googled this and I do not see how a SUM function can help here when I need get the product of two values in this case. Or am I missing something major?
Question: TotalValue is a column in Order relation that contains derived data representing total value (amount) of each order. Write a SQL SELECT statement that computes a value for this column.
My answer:
SELECT Product.ProductPrice * OrderLine.QuantityOrdered AS Total_Value
FROM Product,
OrderLine
GROUP BY Product;
Advice from exam paper:
This is a straightforward question. Tip: you need to use the SUM function. Also, note that you can take the sum of various records set using the GROUP BY clause.
Ok your question became a lot clearer once I clicked on the the hyperlink (blue text).
Each order is going to be made up of a quantity of 1 or more products.
So there could be 3 Product A and 5 Product B etc.
So you have to get the total for each product which is your Price * Quantity, but then you need to add them all together which is where the SUM comes in.
Example:
3 * ProductA Price (e.g. €5) = 15
5 * ProductB Price (e.g. €4) = 20
Total Value = 35
So you need to use the Product, Order and OrderLine tables.
Something like (I haven't tested it):
SELECT SUM(Product.ProductPrice * OrderLine.QuantityOrdered) FROM Product, Order, OrderLine
WHERE Order.OrderID = OrderLine.OrderID
AND Product.ProductID = OrerLine.ProductID
GROUP BY Order.OrderID
This should return rows containing the totalValue for each order - the GROUP BY clause causes the SUM to SUM over each group - not the entire rows.
For a single order you would need add (before the GROUP BY) "AND Order.OrderID = XXXXX" where XXXXX is the actual orders OrderId.

Select inside select

A newbie here. So please be kind :-)
I have 2 Tables namely Item & Item Entries.
Relation is: Item.No = ItemEntries.No.
In Item Entries Table I have Columns as Qty, Entry type, Purchase Amount, Sales Amount
I like to have a report which shows as below,
Item No. | Opening Quantity | Purchase Amount | Sales Amount
To calculate Opening Inventory I summed up the quantity field and the result is as expected. No problem in that. Now From that dataset I like to run a sub query which Calculates/Sum the Purchase amount for an Item that is a part of first dataset and similarly for Sales Amount.
Select(Item No.,Sum(IE.Quantity) As Quantity, Select(......Purchase Amount),Select(....Sales Amount)
I hope I was able to clear my doubts to you guys.
Something like :
SELECT ItemNo, sum(quantity), purchaseAmount, SalesAmount FROM Item i INNER JOIN ItemEntities ie on i.no = ie.no GROUP BY ItemNo, PurchaseAmount, SalesAmount;
I believe (if I understand what you want) that this is the solution to your problem
Select Item.No ,
Sum(IE.Quantity) As Quantity,
(Select(......Purchase Amount)) As ColumnName1 ,
(Select(....Sales Amount)) As ColumnName2
From your need to "sum the purchase amount for an item that is part of the first dataset and similarly for Sales Amount" I think what you're trying to achieve is one row for each item on the Item table with a sum for each of the Qty, Sales Amount and Purchase Amount. If so, then you can simply use a 'group by' clause which groups results together which have matching values for the columns specified.
SELECT I.no, SUM(IE.qty), SUM(IE.purchase_amount), SUM(IE.sales_amount)
FROM item I JOIN item_entries IE
ON I.no = IE.no
GROUP BY I.no;
See the group_by_clause for more details and some examples.
N.B. The join from the item tables isn't strictly required in this example, but if you're producing a report I suspect you might want to get things like a description - in which case you'll need to add those columns to the group by clause too.
You might need the sum of three columns from
ItemEntries table(Qty,PurchaseAmount,SalesAmount) for each Item.No
Select A.No,
Sum(B.Qty),
Sum(B.Purchaseamount),
Sum(B.Salesamount)
From Item A,
Itementries B
Where A.No = B.No
Group By A.No;

Can't get A sum to join to a table

I have two tables, one contains a set of line items with amounts:
LEDGERTRANS:
Invoice ID LineAmount
CM-00011054 -122.500000000000
CM-00011054 -246.000000000000
CM-00011054 -159.840000000000
CM-00011054 -39.3600000000000
And one with an item number i want, which happens to have a field, AMOUNTMST that is the sum of the above amounts
CUSTINVOICETRANS
INVOICE ID AMOUNTMST
110100 -567.700000000000
400100 567.700000000000
I would like to take the sum of the CustInvoiceTrans lines, then grab the corresponding invoice id from the LedgerTrans Table.
This is for SQL Server 2008R2.
As I said, all I want is the InvoiceId. I think i'm making this too complicated. any help appreciated

Multiple of same result even with group by

Alright so say I have a 'product_catalog', and 'orders' tables. Each order has the product_catalog_id as a foreign key. What I want to return as the query results is the product_code (name of the product associated with a specific product_catalog_id) + a count of how many of each product_code have been ordered. That's easy enough with something like this (Oracle SQL):
SELECT pc.product_code,
COUNT(*) as count
FROM orders o
join product_catalog pc on pc.product_catalog_id = o.product_catalog_id
GROUP BY pc.product_code
ORDER BY count DESC;
but I also want to print various pieces of information from the order table such as total of all monthly charges for that product_code. That would seem easy enough with something like this:
(o.monthly_base_charge*count(*)) as "Monthly Fee"
but the problem is that there have been various monthly fees for the same product_code over time. If I add the above line in and add 'o.monthly_base_charge' to the group by statement, then it will print out a unique row for every variation of pricing for that product_code. How do I get it to ignore those price variations and just add together every entry with that product code?
It is a little unclear what you are asking. My best guess is that you want the sum of the monthly base charge:
SELECT pc.product_code,
COUNT(*) as count,
sum(o.monthly_base_charge) as "Monthly Fee"
FROM orders o join
product_catalog pc
on pc.product_catalog_id = o.product_catalog_id
GROUP BY pc.product_code
ORDER BY count DESC;
I'm not sure if this is exactly what you want. What happens if you have two orders in the same month for the same product?
You may need to do something like this since SQL will not be able to know which monthly base charge to multiply by the count.
SELECT pc.product_code,
COUNT(*) as count,
(min(o.monthly_base_charge)*count(*)) as "Monthly Fee"
FROM orders o
join product_catalog pc on pc.product_catalog_id = o.product_catalog_id
GROUP BY pc.product_code
ORDER BY count DESC;
Or you will need to add o.monthly_base_charge to the group by in order for sql to know how to determine the count()
GROUP BY pc.product_code, o.monthly_base_charge

sql SUM value incorrect when using joins and group by

Im writing a query that sums order values broken down by product groups - problem is that when I add joins the aggregated SUM gets greatly inflated - I assume its because its adding in duplicate rows. Im kinda new to SQL, but I think its because I need to construct the query with sub selects or nested joins?
All data returns as expected, and my joins pull out the needed data, but the SUM(inv.item_total) AS Value returned is much higher that it should be - SQL below
SELECT so.Company_id, SUM(inv.item_total) AS Value, co.company_name,
agents.short_desc, stock_type.short_desc AS Type
FROM SORDER as so
JOIN company AS co ON co.company_id = so.company_id
JOIN invoice AS inv ON inv.Sorder_id = so.Sorder_id
JOIN sorder_item AS soitem ON soitem.sorder_id = so.Sorder_id
JOIN STOCK AS stock ON stock.stock_id = soitem.stock_id
JOIN stock_type AS stock_type ON stock_type.stype_id = stock.stype_id
JOIN AGENTS AS AGENTS ON agents.agent_id = co.agent_id
WHERE
co.last_ordered >'01-JAN-2012' and so.Sotype_id='1'
GROUP BY so.Company_id,co.company_name,agents.short_desc, stock_type.short_desc
Any guidence on how I should structure this query to pull out an "un-duplicated" SUM(inv.item_total) AS Value much appreciated.
To get an accurate sum, you want only the joins that are needed. So, this version should work:
SELECT so.Company_id, SUM(inv.item_total) AS Value, co.company_name
FROM SORDER so JOIN
company co
ON co.company_id = so.company_id JOIN
invoice inv
ON inv.Sorder_id = so.Sorder_id
group by so.Company_id, co.company_name
You can then add in one join at a time to see where the multiplication is taking place. I'm guessing it has to do with the agents.
It sounds like the joins are not accurate.
First suspect join
For example, would an agent be per company, or per invoice?
If it is per order, then should the join be something along the lines of
JOIN AGENTS AS AGENTS ON agents.agent_id = inv.agent_id
Second suspect join
Can one order have many items, and many invoices at the same time? That can cause problems as well. Say an order has 3 items and 3 invoices were sent out. According to your joins, the same item will show up 3 times means a total of 9 line items where there should be only 3. You may need to eliminate the invoices table
Possible way to solve this on your own:
I would remove all the grouping and sums, and see if you can filter by one invoice produce an unique set of rows for all the data.
Start with an invoice that has just one item and inspect your result set for accuracy. If that works, then add another invoice that has multiple and check the rows to see if you get your perfect dataset back. If not, then the columns that have repeating values (Company Name, Item Name, Agent Name, etc) are usually a good starting point for checking up on why the duplicates are showing up.