Counting average profit of conditional order - oracle

I have the following table
Order_lines(`Order line`,`order number`,`price`,`sale`,`profit`,`order item`)
Some order numbers have more than one item.
I need to calculate the average profit for the orders that have more than 5 line items.
I put my query like this:
select ROUND(profit/count(item),0) Average Profit
from order_lines;
having count(item)>5;
But it doesn't work. can anyone please help me with this? Thank you so much!!

Nowadays, SQL has a bit of a procedural component to it -- allowing you to break down a problem into multiple, smaller steps.
Try this two-step approach:
SELECT AVG (profit)
FROM (SELECT SUM (profit) profit
FROM order_lines
GROUP BY order_number
HAVING COUNT (*) > 5);
First, we get a list of orders having >5 lines and the profit on each, then we average those profits.

Related

Finding n-th combination with highest sum

I have a list of players and each player has a salary and a rating (both integer values).
I have to find n-th largest combination of 6 players (largest in terms of sum of their ratings) with a constraint that the sum of their salaries must be less or equal than 50000.
For example, if I have a list of players 1,2,...,m, what I'm currently doing is:
Generate all possible 6 player combinations (m choose 6).
Filter out combinations for which sum of salaries is > 50000
Sort remaining combinations in descending order, ordered by sum of ratings
Pick the n-th from the sorted list.
This is obviously a brute force approach which works fine for smaller number of players. But currently I have 140 players which yield over 9 billion combinations and it takes too much to finish.
Any suggestion on how to do this faster?
Here is how you can avoid getting all the combinations.
prepare a descending sorted map with rank as key and salary as value
This will get your ranks sorted on descending order and the first key in the map will be the highest rank. If you have multiple records having the same rank, consider putting them as a list against the same rank.
pick the first 6 top ranks and check if their total salary <= 50000, you get your result, else move to the next 6 combination.
Here if you have more than one record against a rank, try adding their salaries as well.
This will take some patience and some good testing to translate to a program, but will certainly be an optimal solution.

Different behavior of DAX measures depending on nesting

I wanted to calculate the median of the total sales for each category.
If I create the following two measures, it works perfectly:
SoS := SUM(Table1[Sales])
Median Category Sales :=
MEDIANX(
CALCULATETABLE(VALUES(Table1[Category]), ALL(Table1)),
[SoS]
)
However, If I don't nest the measures the median is not calculated and it returns just the sum.
Median without measure :=
MEDIANX(
CALCULATETABLE(VALUES(Table1[Category]), ALL(Table1)),
SUM(Table1[Sales])
)
See results below:
Why this happens? I thought the two approaches were exactly the same.
Actually, the first approach is equivalent to the following:
Median Category Sales :=
MEDIANX(
CALCULATETABLE(VALUES(Table1[Category]), ALL(Table1)),
CALCULATE(SUM(Table1[Sales]))
)
The SoS measure implicitly wraps its formula in a CALCULATE which causes a context transition for each Category provided through VALUES, thereby correctly calculating the sume of sales and therefore the median.

Algorithm to group people based on their preference

I need an algorithm to group people in tables based on their preference. Each person vote sorting the tables from the favorite to the worse.
For example if there are 4 tables in total one person vote is like:
Alice{ table1 => 2, table2 => 4, table3=>1, table4=>3}
which means she would like to be put on table3 and really dislikes table2
The conditions are:
Everyone must be in a group
All groups must have the same number of people (tollerance of 1)
Maximize the global 'happiness'
Trying to sort this out I defined happiness as points, each person will have happiness 10 if they will be put on their favorite table, 6 on their second choice, 4 on the third and 1 on the last.
happiness[10, 6, 4, 1]
The global happiness is the sum of each person's happiness.
One way to solve this is to use integer linear programming.
There are many solvers out there for ILP, for example SCIP (http://scip.zib.de/).
You would have binary variable for each assigment, i.e.
= 1 if person i was assigned to table j (and 0 is it was not assigned).
Your goal is to maximize total happiness, i.e. sum of weights multiplied by
Now you have write some conditions to ensure, that:
each person is assigned to exactly one table, i.e. sum of for each i is equal to one.
all tables have similar number of persons (you can determine possible ranges for number of persons beforehand), i.e. some of for each j is in defined range.

Find combination of products for max profit

I have a problem where I have to find out the best combination of products which can yield maximum profit.
Suppose I have 3 products (A,B and C). The Unit cost of each product respectively is ($a, $b and $c). The inflation rate for A,B and C is (p%, q% and r%) i.e. every time user purchase a product, its unit cost increases by the said inflation rate. User can only purchase the product in lot of (l,m and n) quantities respectively. Each product gives a profit of $x, $y and $z respectively per unit.
So for a single round of purchase, for product A,
Total Cost = l*$a
Total Profit = l*$x
Unit price after purchase = ((p/100)*$a)+$a
How can I find the right combination of purchase of A,B and C, which will give me maximum profit.
I referred internet and found something called "Optimal Product Mix" problem given here...
http://www.technicalcommunicationcenter.com/2013/03/29/how-to-calculate-optimal-product-mix-with-ms-excel-2010-solver-to-maximize-profits/
However, somehow I am not able to relate it which my problem statement.
Can someone suggest me a way to solve this?
Thanks
If your budget is significantly larger than the price of a single lot, a greedy algorithm should get you close to an optimal solution - iteratively select the lot that you can afford that gives you the most profit right now until all options are no longer profitable.
If your budget is not significantly larger than a single lot, or you must solve for the globally optimal solution, this reduces to the knapsack problem.
If your budget is unlimited, simply buy enough lots of each item to make the profit go negative, then stop - the greedy algorithm will lead to the same result.

If you know the future prices of a stock, what's the best time to buy and sell?

Interview Question by a financial software company for a Programmer position
Q1) Say you have an array for which the ith element is the price of a given stock on
day i.
If you were only permitted to buy one share of the stock and sell one share
of the stock, design an algorithm to find the best times to buy and sell.
My Solution :
My solution was to make an array of the differences in stock prices between day i and day i+1 for arraysize-1 days and then use Kadane Algorithm to return the sum of the largest continuous sub array.I would then buy at the start of the largest continuous array and sell at the end of the largest
continous array.
I am wondering if my solution is correct and are there any better solutions out there???
Upon answering i was asked a follow up question, which i answered exactly the same
Q2) Given that you know the future closing price of Company x for the next 10 days ,
Design a algorithm to to determine if you should BUY,SELL or HOLD for every
single day ( You are allowed to only make 1 decision every day ) with the aim of
of maximizing profit
Eg: Day 1 closing price :2.24
Day 2 closing price :2.11
...
Day 10 closing price : 3.00
My Solution: Same as above
I would like to know what if theres any better algorithm out there to maximise profit given
that i can make a decision every single day
Q1 If you were only permitted to buy one share of the stock and sell one share of the stock, design an algorithm to find the best times to buy and sell.
In a single pass through the array, determine the index i with the lowest price and the index j with the highest price. You buy at i and sell at j (selling before you buy, by borrowing stock, is in general allowed in finance, so it is okay if j < i). If all prices are the same you don't do anything.
Q2 Given that you know the future closing price of Company x for the next 10 days , Design a algorithm to to determine if you should BUY,SELL or HOLD for every single day ( You are allowed to only make 1 decision every day ) with the aim of of maximizing profit
There are only 10 days, and hence there are only 3^10 = 59049 different possibilities. Hence it is perfectly possible to use brute force. I.e., try every possibility and simply select the one which gives the greatest profit. (Even if a more efficient algorithm were found, this would remain a useful way to test the more efficient algorithm.)
Some of the solutions produced by the brute force approach may be invalid, e.g. it might not be possible to own (or owe) more than one share at once. Moreover, do you need to end up owning 0 stocks at the end of the 10 days, or are any positions automatically liquidated at the end of the 10 days? Also, I would want to clarify the assumption that I made in Q1, namely that it is possible to sell before buying to take advantage of falls in stock prices. Finally, there may be trading fees to be taken into consideration, including payments to be made if you borrow a stock in order to sell it before you buy it.
Once these assumptions are clarified it could well be possible to take design a more efficient algorithm. E.g., in the simplest case if you can only own one share and you have to buy before you sell, then you would have a "buy" at the first minimum in the series, a "sell" at the last maximum, and buys and sells at any minima and maxima inbetween.
The more I think about it, the more I think these interview questions are as much about seeing how and whether a candidate clarifies a problem as they are about the solution to the problem.
Here are some alternative answers:
Q1) Work from left to right in the array provided. Keep track of the lowest price seen so far. When you see an element of the array note down the difference between the price there and the lowest price so far, update the lowest price so far, and keep track of the highest difference seen. My answer is to make the amount of profit given at the highest difference by selling then, after having bought at the price of the lowest price seen at that time.
Q2) Treat this as a dynamic programming problem, where the state at any point in time is whether you own a share or not. Work from left to right again. At each point find the highest possible profit, given that own a share at the end of that point in time, and given that you do not own a share at the end of that point in time. You can work this out from the result of the calculations of the previous time step: In one case compare the options of buying a share and subtracting this from the profit given that you did not own at the end of the previous point or holding a share that you did own at the previous point. In the other case compare the options of selling a share to add to the profit given that you owned at the previous time, or staying pat with the profit given that you did not own at the previous time. As is standard with dynamic programming you keep the decisions made at each point in time and recover the correct list of decisions at the end by working backwards.
Your answer to question 1 was correct.
Your answer to question 2 was not correct. To solve this problem you work backwards from the end, choosing the best option at each step. For example, given the sequence { 1, 3, 5, 4, 6 }, since 4 < 6 your last move is to sell. Since 5 > 4, the previous move to that is buy. Since 3 < 5, the move on 5 is sell. Continuing in the same way, the move on 3 is to hold and the move on 1 is to buy.
Your solution for first problem is Correct. Kadane's Algorithm runtime complexity is O(n) is a optimal solution for maximum subarray problem. And benefit of using this algorithm is that it is easy to implement.
Your solution for second problem is wrong according to me. What you can do is to store the left and right index of maximum sum subarray you find. Once you find have maximum sum subarray and its left and right index. You can call this function again on the left part i.e 0 to left -1 and on right part i.e. right + 1 to Array.size - 1. So, this is a recursion process basically and you can further design the structure of this recursion with base case to solve this problem. And by following this process you can maximize profit.
Suppose the prices are the array P = [p_1, p_2, ..., p_n]
Construct a new array A = [p_1, p_2 - p_1, p_3 - p_2, ..., p_n - p_{n-1}]
i.e A[i] = p_{i+1} - p_i, taking p_0 = 0.
Now go find the maximum sum sub-array in this.
OR
Find a different algorithm, and solve the maximum sub-array problem!
The problems are equivalent.

Resources