I am new to sql and I am attempting to write a query that takes a maximum after two separate columns are multiplied together.
One table is called portfolio and contains the amount of shares purchased. The other table is called investment and has the price paid. I am just trying to get the highest (max) purchase price after multiplying the two values. Any help would be appreciated.
Assuming that all you want is the overall max, and that the price paid stored in the investment table is the 'quantity' column and the number of shares purchased is the 'amount' column on the portfolio table, AND that the link between the portfolio and investment tables is the 'port_id' you want something like this:
SELECT MAX(t2.amount * t1.quantity) AS 'Max Purchase Price'
FROM Investment t1
JOIN Portfolio t2 ON t1.port_id = t2.port_id
If you need more columns you can add them to the SELECT list and you'll need to add in a GROUP BY (plenty of posts on SO related to this). Hope this helps!
Related
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially the seller's price? Right now I have my database schema so the product table stores the recommended price and the seller's price, and that means one single product is repeated a lot of times. Is there a better way to do this?
Per the recommendations below this is the correct db schema:
Since you have a case of many-to-many then your structure would use a link table. You’ll have tables seller, product and link_seller_product. The last table has a link to the seller table via id as well as the product table via id. This table therefore can also have any information that is dependent on the seller and the product and is not fixed for either. So price-per-product-per-seller goes there.
So add the additional link table with columns sellerid, productid and price and you’ll have only single rows in sellers and products but each seller can have their own price for the product.
You're not adequately representing the one-to-many relationship between products and sellers. Your product table has the seller_id and the seller_price, but if one product is sold by many sellers, it cannot.
Instead of duplicating product entries so the same product can have multiple sellers, what you need is a table between products and sellers.
CREATE TABLE seller_products (
seller_id integer,
product_id integer,
price decimal
);
I'll leave the indexes foreign keys etc to you. Seller ID and product ID might be a unique combination ( historical data is best removed from active datasets for performance longevity ) , but of course any given product will be listed once for each seller that sells it and any given seller will be listed once per product it sells ( along with its unique price).
Then you can join the table back to products to get the data you currently store denormalized in the products table directly :
SELECT *
FROM products
LEFT JOIN seller_products ON ( seller_products.product_id = products.id)
This is a Data Warehouse question.
I would recommend putting prices on a Fact as measures and having only attributes on the Dimensions.
Dimensions:
Product
Seller
Manufacturer
Fact (Columns):
List item
Seller Price
List item
MRSP
Product ID
Seller ID
Manufacturer ID
Timestamp
I've been working on an exercise for school that should have been rather simple. For some reason I cant quite figure out where I went wrong. I have been at it awhile so I may be overlooking something simple. I have some experience with data bases and actually implemented sqlite earlier today in an app but access is throwing me for a loop ! Any help is much appreciated.
Directions:
create a relationship between the tblEmployee table and the tblDepartment table as well as between the tblEmployee and the tblSale table. Be sure to enforce referential integrity in both relationships.
Create a query in Design view using the tblEmployee, tblProduct, tblSale, and tblSaleDetail tables. Add the First, Last, and Active? fields (in that order) to the query. Make the following changes to the query:
Display only active employees.
In the first empty column, calculate a new field, Total Sales (UnitPrice * Quantity) for each active employee.
Only display employees with more that than $300.00 in Total Sales.
Calculate a new field, Total Revenue (Total Sales – (Coupon * Quantity)) for each active employee.
Sum the UnitPrice, Quantity, Coupon, Total Sales, and Total Revenue fields.
Show First, Last, Total Sales, and Total Revenue in the query results.
Access Setup
When I run the query
Why is Total Sales not populated from that equation ?
Also, im a little unclear on where to add the > 300.00 to filter on employee sales.
The issue here isn't the total sales column, it is that you refer to a calculated field total sales when you create a column called total revenue.
Total Sales is only calculated once the query has been run, but total revenue wants to know what the value is before the query is run.
A workaround for this is to use the same calculation:
total revenue: ([Quantity]*[UnitPrice])-([coupon]*[quantity])
Another workaround is to create a query that calculates total sales. You can then insert that query into this one and use it as a subquery.
As for the ">300 for employee sales". I think the following may work:
I assume this is a monetary value by the 2 decimal places and not a 'number of sales' value. Therefore, I would add a new column.
SumOfSales: sum([tblSales].[quantity]*[tblSales].[UnitPrice])
Criteria: >300.00
Show: unticked
I am designing an e-commerce website that has the following scenario:
A customer can purchase items and create an order.
The order may have unknown fee that will be added after the customer
pays the total amount of the items. That is, the customer pays
certain amount first. The order adds some fee and changes the total.
And the customer pays again for the difference. But the two (or
more) payments are associated with the same order.
(Optional) The customer can submit a single payment for multiple
orders.
Currently, I have an Order table and each order may consist of multiple OrderLineItems (simplified schema):
Order
=====
customer
line_items
total
status
OrderLineItem
=============
price
quantity
order
product
A payment is associated with an order (simplified schema):
Payment
=======
order
payment_account
total
result
It seems to be very hard to support the multiple payments for a single order scenario in the current implementation. I reckon that I have to introduce immutable invoices in the system, and the payment should be associated with an invoice instead of an order. However, I would need some help with the order/invoice/payment modeling for the above scenario. Some specific questions I have:
An order and an invoice look very similar to me (e.g. both have
items and totals). What is the major difference in typical
e-commerce systems?
How should I model invoices for my scenario? Should I have
OrderLineItems for an Order AND InvoiceLineItems for an Invoice?
Some preliminary thoughts: I will have multiple invoices associated
with a certain order. Whenever the order changes the total, I have
to somehow calculate the difference and send a new/immutable invoice
to the customer. Then, the customer can pay and the payment will be
associated with the invoice.
Would love to hear some advice. Much appreciated. Thanks!
There are a lot of questions here, I'll try to address as many as I can. A lot of the issues are the business model rather than the data model.
Firstly, you are right that you need an immutable invoice. Once an invoice is created you cannot alter it, the standard way of handling a change in invoice is to issue a credit note and a new invoice.
Think about the relations between the tables: the Order does not need to hold the lineItems as these are referenced the other way, i.e.
Order
=====
orderId
customerId
status
OrderLineItem
=============
orderLineItemId
orderId
product
price
quantity
So to view the order you join the tables on orderId. There's also no need to store the total as that is calculated from the join.
Try not to duplicate your data: your invoice will reference orderLineItems, but not necessarily the same ones in the order. For example, the customer orders an A and a B, but B is out of stock. You ship A and create an invoice that references orderLineItemId for A. So your invoice tables might look like:
invoice
=======
invoiceId
status
invoiceLineItem
===============
invoiceId
orderLineItemId
quantity
In other words there's no need to have the details of the item. You may be wondering why you don't just add an invoiceId to the orderLineItem table - the reason is the customer might order 10 of item A, but you only ship 8 of them, the other two will go on a subsequent invoice.
Payments are not made against orders, they are against invoices. So your payments table should reference the invoiceId.
Then you touch on reconciliation. If everything was perfect, the customer would make a payment against a particular invoice, even if a partial payment. In reality this is going to be your biggest headache. Suppose the customer has several outstanding invoices for amounts x, y and z. If they make a payment of p, which do you allocate it against? Perhaps in date order, so that if p>x the remainder is allocated against y. What if p=z? Perhaps the customer is intending to pay z now but is disputing y and has mislaid x? How you deal with these sorts of things is up to you, but I can say that most invoicing systems do it very badly indeed.
I need a little help designing a database that a bar would use for drinks. My app handles drink orders in 2 ways: A customer can order drinks and pay right away, or they can start a tab. This is my table relationship so far:
Table Order: Table Tabs:
------------ ------------
[PK] OrderId - 1 [PK] TabId
ItemName / TabName
QtyOrdered / Total
TabId *- PaymentType
Archive
Its setup so 1 tab can have many drinks on it. Thats great for tabs, but customers can choose not to setup a tab. My question is, how can i modify these two tables to support that? Or do I have to create a new table?
Thanks in advance.
Your "item" is the order line-item.
"My brother and I will each have a Guiness and his wife would like a gin-and-tonic."
There are three (EDIT: items, but two) line-items on that order. To identify them as part of the same order [if you should need to do so], you would need two tables:
the OrderHeader
(orderheaderid, orderdatetime, customerid)
and
the OrderDetail
(id, orderheaderid, drinkid, howmany, extendedprice, paymentamountapplied).
If you do not need to identify the drinks as belonging to the same order, you could abandon the two-table structure, but then you could have only one kind of drink per order.
ORDER
orderid, orderdatetime, customerid, drinkid, howmany, extendedprice, paymentapplied.
Extended price is howmany * the drink's price at time of the order. You store this value in your order table so you can change the price of the drink in the DRINKS table without affecting the tab amount owed (in case the tab lifetime is longer than a day -- i.e. customers can run a monthly or quarterly tab).
HowMany can default to 1. The amount owed on a drink line-item is (extendedprice - paymentamountapplied). PaymentAmountApplied defaults to 0 (i.e. default is to run a tab).
If you do not need to track the kind of drink being ordered (i.e. you don't care to use your database to discover that on Tuesday nights you sell a lot more gins-and-tonic than Guinesses, for some reason):
ORDER
orderid, orderdatetime, customerid, ordertotal, paymentapplied.
Your barkeep would simply enter the total amount of the order, calculated outside your system, without reference to a DRINKS table in the database -- maybe the barkeep would look at a chalkboard on the wall.
You need a CUSTOMERS table, a DRINKS table, an ORDERSHEADER table, an ORDERDETAIL table (each drink on the tab is a line-item). You could/should have a separate PAYMENTS table. And you would allocate payments to the line-items of the ORDERDETAIL (your tab). The "tab" is the set of all line-items on the order(s) that have no payment applied to them.
I have problem with two parts of database diagram and I need your guidance:)
database has a lot of tables that one of them is about Employee ,the other is about Customer and ... ! I have problem with two tables (Product and OrderDetail) my Product table has 3 columns (ProductID,Name,Cost) and the Other table is OrderDetail that has these columns(OrderDetailID,Cost,Quantity) I have not created this database myself I have found it like a sample database in the internet but I have problem about these two Cost which is in OrderDetail and Product tables ,what is the difference between these Cost? they are the same or not?
thanks
EDITED: sorry all I had a mistake ,the ID for the ordeDetail table is the composite of primary key of Product table and Order table which is Product ID and OrderID and the OrdeDeatil table is a weak entity. SO
OrderDeatil((ProductID,OrderID),Cost,Quantity)
I suppost that the cost in the products table is the current price of the product. On the other hand, the cost in the order details table is the price that was paid for the product for that particular order.
Product prices can go up or down, or discounts might have been given for particular orders. The field in the order details table would store this information.
UPDATE: Further to your updated question, that makes sense. It implies that each order can only list the same product once. The order details table is storing how many items of that product were ordered (quantity) and I would say that cost is the price paid for one item. It could be the total (price * quantity) but that's not a common for such table structures.
Without knowing exactly what this database is meant to capture, I couldn't say for sure, but as a rough guess I would expect that the Product tables Cost column is the cost for a single unit of that product, and the OrderDetail tables Cost column is the cost for an order of some quantity of 'something' - most likely a certain quantity of a product. Note as an interesting aside that there is nothing linking the OrderDetail table to the Product table - if these two tables are meant to be linked you would normally expect a Foreign Key in the OrderDetail table linking it to the Product table. At the moment, there is no way to match OrderDetails to Products.