Difference between AUFK-AUFNR and AUFK-KDAUF - sap-erp

There are two fields in the SAP table AUFK, AUFNR and KDAUF, that I cannot differentiate. I searched around in the net, and both are being referred to as "Sales Order Number".
Can somebody kindly explain what the differences are between the two?

AUFNR is not the sales order number. Table AUFK stores the internal orders of the CO module, AUFNR is its number, so the internal order number. Internal order is a CO element (like a cost center), you can post on them. KDAUF is the sales order number (you can post sales orders on internal orders, this is why it is there).

Related

Why are Duplicates not being filtered out

I am working on some practice interview Questions and am struggling with this:
You are working with a company that sells goods to customers, and they'd like to keep track
of the unique items each customer has bought. The database is composed of two tables:
Customers and Orders. The two table schemas are given below. We want to know what
unique items were purchased by a specific customer, Wilbur, and when they were
purchased. What is the correct query that returns the customer first name, item
purchased, and purchase date with recent purchases first?
Tables: https://imgur.com/a/D47R1KU
My answer so far is
However I am getting an incorrect message as its Printing wilbur,oranges,2019-06-10
and wilbur,oranges,2018-06-10 instead of just the one with the more recent date. Please see the picture for the two tables referenced by the question. Thanks!
Between the where clause and ORDER BY, try:
GROUP BY FirstName, Item
And to get the most recent date, select MAX(PurchaseDate).
The query you are looking for is as follows.
This uses group by to indicate which columns should be grouped together, and for the column that's not grouped, how to choose which value of many to use, in this case the max value.
Note also the use of explicit, clear, SQL-92 modern join syntax and meaningful column aliases to show which table each column originates from. Distinct is not needed since each group is already unique.
Select c.FirstName, o.Item, Max(o.PurchaseDate) PurchaseDate
from Customers c
join Orders o on o.PersonId=p.PersonId
where c.FirstName = 'Wilbur'
group by c.firstName, o.Item
order by Max(o.PurchaseDate) desc;

MySQL - When shouldn't I Join tables? Combinatorial Explosion of values

I am working on a database called classicmodels, which I found at: https://www.mysqltutorial.org/mysql-sample-database.aspx/
I realized that when I executed an Inner Join between 'payments' and 'orders' tables, a 'cartesian explosion' occurred. I understand that these two tables are not meant to be joined. However, I would like to know if it is possible to identify this just by looking at the relational schema or if I should check the tables one by one.
For instance, the customer number '141' appears 26 times in the 'orders table', which I found by using the following code:
SELECT
customerNumber,
COUNT(customerNumber)
FROM
orders
WHERE customerNumber=141
GROUP BY customerNumber;
And the same customer number (141) appears 13 times in the payments table:
SELECT
customerNumber,
COUNT(customerNumber)
FROM
payments
WHERE customerNumber=141
GROUP BY customerNumber;
Finally, I executed an Inner Join between 'payments' and 'orders' tables, and selected only the rows with customer number '141'. MySQL returned 338 rows, which is the result of 26*13. So, my query is multiplying the number of times this 'customer n°' appears in 'orders' table by the number of times it appears in 'payments'.
SELECT
o.customernumber,
py.amount
FROM
customers c
JOIN
orders o ON c.customerNumber=o.customerNumber
JOIN
payments py ON c.customerNumber=py.customerNumber
WHERE o.customernumber=141;
My questions is the following:
1 ) Is there a way to look at the relational schema and identify if a Join can be executed (without generating a combinatorial explosion)? Or should I check table by table to understand how the relationship between them is?
Important Note: I realized that there are two asterisks in the payments table's representation in the relational schema below. Maybe this means that this table has a composite primary key (customerNumber+checkNumber). The problem is that 'checkNumber' does not appear in any other table.
This is the database's relational schema provided by the 'MySQL Tutorial' website:
Thank you for your attention!
This is called "combinatorial explosion" and it happens when rows in one table each join to multiple rows in other tables.
(It's not "overestimation" or any sort of estimation. It's counting data items multiple times when it should only count them once.)
It's a notorious pitfall of summarizing data in one-to-many relationships. In your example each customer may have no orders, one order, or more than one. Independently, they may have no payments, one, or many.
The trick is this: Use subqueries so your toplevel query with GROUP BY avoids joining one-to-many relationships serially. In the query you showed us, that's happening.
You can this subquery to get a resultset with just one row per customer. (try it.)
SELECT customernumber,
SUM(amount) amount
FROM payments
GROUP BY customernumber
Likewise you can get the value of all orders for each customer with this
SELECT c.customernumber,
SUM(od.qytOrdered * od.priceEach) amount
FROM orders o
JOIN orderdetails od ON o.orderNumber = od.orderNumber
GROUP BY c.customernumber
This JOIN won't explode in your face because customer can have multiple orders, and each order can have multiple details. So it's a strict hierarchical rollup.
Now, we can use these subqueries in the main query.
SELECT c.customernumber, p.payments, o.orders
FROM customers c
LEFT JOIN (
SELECT c.customernumber,
SUM(od.qytOrdered * od.priceEach) orders
FROM orders o
JOIN orderdetails od ON o.orderNumber = od.orderNumber
GROUP BY c.customernumber
) o ON c.customernumber = o.customernumber
LEFT JOIN (
SELECT customernumber,
SUM() payment
FROM payments
GROUP BY customernumber
) p on c.customernumber = p.customernumber
Takehome tricks:
A subquery IS a table (a virtual table) that can be used whereever you might mention a table or a view.
The GROUP BY stuff in this query happens separately in two subqueries, so no combinatorial explosions.
All three participants in the toplevel JOIN have either one or zero rows per customernumber.
The LEFT JOINs are there so we can still see customers with (importantly for a business) no orders or no payments. With the ordinary inner JOIN, rows have to match both sides of the ON conditions or they're omitted from the resultset.
Pro tip Format your SQL queries fanatically carefully: They are really verbose. Adm. Grace Hopper would be proud. That means they get quite long and nested, putting the Structured in Structured Query Language. If you, or anybody, is going to reason about them in future, we must be able to grasp the structure easily.
Pro tip 2 The data engineer who designed this database did a really good job thinking it through and documenting it. Aspire to this level of quality. (Rarely reached in the real world.)
In this particular case, your behavior should depend on the accounting style being supported by the database, and this does not appear to be "open item" style accounting ie when an order is raised for 1000 there does not need to be a payment against it for 1000.. This is perhaps unusual in most consumer experience because you will be quite familiar with open item style ordering from Amazon - you buy a 500 dollar tv and a 500 dollar games console, the order is a thousand dollars and you pay for it, the payment going against the order. However, you're also familiar with "balance forward" accounting if you paid for that order using your credit card because you make similar purchases every day for a month and hen you get a statement from your bank saying you owe 31000 and you pay a lump of money, doesn't even have to be 31k. You aren't expected to make 31 payments of 1000 to your bank at the end of the month. Your bank allocate it to the oldest items on the account (if they're nice, or the newest items if they're not) and may eventually charge you interest on unpaid transactions
1 ) Is there a way to look at the relational schema and identify if a Join can be executed
Yes, you can tell looking at the schema- customer has many orders, customer makes many payments, but there is no relation between the order and payment tables at all so we can see there is no attempt to directly attach a payment to an order. You can see that customer is a parent table of payment and order, and therefore enjoys a relationship with each of them but they do not relate to each other. If you had Person, Car and Address tables, a person has many addresses during their life, and many cars but it doesn't mean there is a relationship between cars and addresses
In such a case it simply doesn't make sense to join payments to customers to orders because they do not relate that way. If you want to make such a join and not suffer a Cartesian explosion then you absolutely have to sum one side or the other (or both) to ensure that your joins are 1:1 and 1:M (or 1:1 and 1:1). You cannot arrange a join that is a pair of 1:M.
Going back to the car/person/address example to make any meaningful joins, you have to build more information into the question and arrange the join to create the answer. Perhaps the question is "what cars did they own while they lived at" - this flattens the Person:Address relationship to 1:1 but leaves Person:Car as 1:M so they might have owned many cars during their time in that house. "What was the newest car they owned while living at..." might be 1:1 on both sides if there is a clear winner for "newest" (though if they bought two cars manufactured at identical times...)
Which side you sum in your orders case will depend on what you want to know, but in this case I'd say you usually want to know "which orders haven't been paid for" and that's summing all payments and rolling summing all orders then looking at what point the rolling sum exceeds the sum of payments.. those are the unpaid orders
Take a look again at your database graph (the one that was present in the first iteration of your question). See the lines between tables have 3 angled legs on one end - that's the many end. You can start at any table in the graph and join to other tables by walking along the relationship. If you're going from the many end to the one end, and assuming you've picked out a single row in the start table (a single order) you can always walk to any other table in the many->one direction and not increase your row count. If you walk the other way you potentially increase your row count. If you split and walk two ways that both increase row count you get a Cartesian explosion. Of course, also you don't have to only join on relation lines, but that's out of scope for the question
ps: this is easier to see on the db diagram than the ERD in the question because the database purely concerns itself with the columns that are foreign keyed. The ERD is saying a customer has zero or one payments with a particular check number but the database will only be concerned with "the customer ID appears once in the customer table and multiple times in the payment table" because only part of the compound primary key of payment is keyed to the customer table. In other words, the ERD is concerned with business logic relations too, but the db diagram is purely how tables relate and they aren't necessarily aligned. For this reason the db diagrams are probably easier to read when walking round for join strategies
After seeing the answers of Caius Jard and O.Jones (please, check their replies), which kindly helped me to clarify this doubt, I decided to create a table to identify which customers paid for all orders they made and which ones did not. This creates a pertinent reason to join 'orders', 'orderdetails', 'payments' and 'customers' tables, because some orders may have been cancelled or still may be 'On Hold', as we can see in their corresponding 'status' in the 'orders' table. Also, this enables us to execute this join without generating a 'combinatorial explosion'.
I did this by using the CASE statement, which registers when py.amount and amount_in_orders match, don't match or when they are NULL (customers which did not make orders or payments):
SELECT
c.customerNumber,
py.amount,
amount_in_orders,
CASE
WHEN py.amount=amount_in_orders THEN 'Match'
WHEN py.amount IS NULL AND amount_in_orders IS NULL THEN 'NULL'
ELSE 'Don''t Match'
END AS Match
FROM
customers c
LEFT JOIN(
SELECT
o.customerNumber, SUM(od.quantityOrdered*od.priceEach) AS amount_in_orders
FROM
orders o
JOIN orderdetails od ON o.orderNumber=od.orderNumber
GROUP BY o.customerNumber
) o ON c.customerNumber=o.customerNumber
LEFT JOIN(
SELECT customernumber, SUM(amount) AS amount
FROM payments
GROUP BY customerNumber
) py ON c.customerNumber=py.customerNumber
ORDER BY py.amount DESC;
The query returned 122 rows. The images below are fractions of the generated output, so you can visualize what happened:
For instance, we can see that the customers identified by the numbers '141', '124', '119' and '496' did not pay for all the orders they made. Maybe some of them where cancelled or maybe they simply did not pay for them yet.
And this image shows some of the columns (not all of them) that are NULL:

Number of vendors available for each product, number of PurchaseOrderIDs where these top products are present

Written the Top 10 Products based on the number of Vendors available for each product.
Also, display the number of PurchaseOrderIDs where these top products are present.
select
top 10 pod.productid,
count(vendorid)as no_of_vendors,
count(poh.purchaseorderid)as no_of_purorder
from purchasing.purchaseorderdetail pod join purchasing.purchaseorderheader poh on
pod.purchaseorderid=poh.purchaseorderid
group by pod.productid order by count(vendorid) desc
I can't get the correct output. I used adventure works 20012. Please suggest an answer for this query.
select
top 10 pod.productid,
count(DISTINCT(vendorid))as no_of_vendors,
count(poh.purchaseorderid)as no_of_purorder
from purchasing.purchaseorderdetail pod join purchasing.purchaseorderheader poh on
pod.purchaseorderid=poh.purchaseorderid
group by pod.productid order by count(DISTINCT(vendorid)) desc, count(poh.purchaseorderid) DESC
Without DISTINCT, it's just counting the same thing as the number of purchase orders. I don't think it matters in this data here, but I would also point out that if an item appeared twice on the same purchase order, it would also double-count that if there was no DISTINCT used on that. I am also, by the way, assuming that because there are so many products that have just three vendors that you wanted it further ranked by the number of purchase orders for that product.

MS Access: Report to contain info from third table

I'm currently working on a database for a company, for them to use when making production orders. A report is to be made consisting of several things, mainly product number, order number etc etc. A part of the report is to be made up of a list of spare parts needed for the production of the item in question. I have a table with an order number and product number, which needs to look in another table to find the necessary spare parts. However, the name, location and stock of those spare parts are in a third table, and I can't seem to find a way to include these things automatically when the product number is known. I'm pretty new to MS Access, so any help will be greatly appreciated. Thanks!
I have a table called Table1, which uses a combobox to automatically fill boxes such as production time, test time etc from a given product number. This data is gathered from the second table StandardTimes, which has as a primary key the product number. Other columns in this table includes production area, standard quantity, average production time, and also includes in several columns, the necessary spare parts needed. In a third table called Inventory, we have the product numbers of the spare parts, their location in storage, and number of items currently in store. I created a report using a query which takes an order number, and creates a report on that order number from Table1. What needs to be included in this report is a list of the spareparts necessary, the location in the storage, and the number of items currently in store.
Revised from new user input
Your question still does not provide actual columns or data. As a result, it's hard to model your needs.
However, based on what I can read, I think that you have are missing some basic design setup items in a relational model.
Assuming that you have 3 tables: Table1 (Orders), StandardTimes (Products) and Inventory (SpareParts)
In English, every order has one or more products. Every product has one or more spare parts. Really you'd want an orders table, and an order details table which has records for each item as part of that order. But I'm answering it on your setup which I believe is flawed.
Orders <-(1:M)-> Products <- (1:M) -> SpareParts
You have an OrderID, a ProductID, and a SparePartID.
A query such as this would join those 3 tables together with that kind of relationship.
SELECT o.OrderNum, o.ProductNum, st.ProductionArea, st.StandardQuality, i.SparePartsNum, i.Location, i.Qty
FROM Orders as o
INNER JOIN StanardTimes as st on o.ProductNum = st.ProductNum
INNER JOIN Inventory as i on i.ProductNum = st.ProductNum
Some sample data would be helpful to help design the queries.
In principal you would need to join the tables together to get the desired result.
You would join the productID on tblOrders to the ProductID on tblProducts. This will net you the name of the product etc.
This would be an INNER join, as every order has a product.
You would then join to tblSpareParts, also using the productID so that you could return the status of the spare parts for that product. This might be a LEFT JOIN instead of an INNER, but it depends on if you maintain a value of 0 for spare parts (e.g. Every product has a corresponding spare parts record), or if you only maintain a spare parts record for items which have spare parts.

how to design the tables for customer orders and bills

Am designing a database schema (orders and bills) for a hotel system.
The attached image shows the tables in the database schema.
The question is how do I design the bills table, so that I can calculate the customer bill from orders the customer has made?
My assumption is that a bill is calculated after the order is made, and not the other way round, e.g. creating a bill before we make an order.
I am considering this answer however it does not solve my problem, since I want to calculate bills from customer orders.
The red rectangle shows the relationship between the orders and bill table this is where am stuck, I don't know how to design the tables.
Some language standardization first:
By Order you mean Sales Order, OrderDetails are called Line Items, and a Bill is usually called a Sales Invoice.
An sales invoice is a request for payment. You issue one when you think someone owes you money.
Depending on the terms of the sales order, someone owes you money:
after the order is completed
after the service is first delivered
after the service is completely delivered
after some period of time based on the terms of the sales order
For a hotel, usually you ask for money after the service has been completely delivered, but perhaps with a deposit, or intermediate payments for a long stay.
An invoice is not necessarily for one sales order. You can combine multiple sales orders into one invoice.
An invoice has line items referencing the sales order line items that you are requesting payment for.
You may have to issue multiple invoices for the same person/sales order.
EDIT 3 added design + cleanup
Every base table is the rows satisfying some statement. Find the statement.
Customer is the rows satisfying: customer [CustomerId] named [CustomerName] lives at ...
Product is the rows satisfying: product [ProductId] is named [Productname] costing [ProductPrice]
OrderDetail is the rows satisfying: orderDetail [OrderDetailId] of order [OrderId] is quantity [quantity] of product [ProductId]
Order is the rows satisfying: customer [CustomerId] ordered [OrderId] on [dateOfOrder]
What rows do you want in Bill? I'll guess...
Bill is the rows satisfying:
Bill [BillId] is for order [OrderId] on [dateOfBill] ... ???
You can find out some things about a bill by using its order. You must determine what else besides its date and order that you want know about a bill (eg to write one) and then what statement bill rows satisfy (ie finish the "...") that gives you that info directly (as with its date) or indirectly (as with its order).
I asked
what else besides its date and order that you want know about a bill (eg to write one)
BillId
dateOfBill
OrderId
order OrderId's customer's CustomerId, CustomerName, CustomerAddress ...
order OrderId's dateOfOrder
for every orderDetailId's orderDetail whose orderID = OrderId
quantity, ProductId, ProductNam,e ProductPrice, (quantity * ProductPrice) as productProduct
sum(quantity * ProductPrice) as total
over every orderDetail with OrderDetailId = OrderId
I asked
what statement bill rows satisfy that gives you that info directly or indirectly
You suggested
For the bills table I intend to have the following fields
Bill BillId (PK) CustomerId (FK) OrderId (FK) dateOfBill
Bill has to directly give us a BillId, dateOfBill and OrderId; they're nowhere else. But everything else can be got indirectly.
Bill is the rows satisfying:
bill [BillId] is for order [OrderId] and was billed on [dateOfBill]
The reason I mention statements is: one needs them to query and to determine FDs, keys, uniqueness, Fks, and other constraints. (Rather than using one vague intuitions.) This is explicit in design methods ORM2, NIAM and FCO-IM.
I determined the content of a bill above by finding what statement its rows will satisfy:
customer [CustomerId] named [CustomerName] at [CustomerAddress] ...
owes us $[total] for order [OrderId]
ordering [quantity] of product [ProductId] named [ProductName] # price $[ProductPrice] = [productProduct]
as recorded in bill [BillId]
This is a statement made from the statements given for each table, except that I need some statements not in any table yet, namely the stuff that (therefore) Bill needs to give. By replacing the statements by their tables we will get the query whose values are the rows we want.