MySQL - Calculating profit from joining two tables [closed] - mysql

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So I have two tables,
one has the product margin before tax, and
other table has the individuals products tax % (unfortunately in whole number format).
The code I'm using works, but some products are not taxed, and therefore have 0.
I'm trying to figure out how calculate their profit with the same formula I'm using.
SELECT o.product_id,
(((o.total_margin/1000)-(p.tax/100)*o.total_margin/1000)/1000) AS Profit
FROM merproduct_offers o
JOIN merchant_products p ON o.product_id = p.product_id
WHERE p.tax > '1'
Linked below are screenshots of the two tables I'm using. Thanks again!

You seem to want a left join and coalesce():
SELECT
o.product_id,
(((o.total_margin/1000)-(COALESCE(p.tax, 0)/100)*o.total_margin/1000)/1000) AS Profit
FROM merproduct_offers o
LEFT JOIN merchant_products p
ON o.product_id = p.product_id AND p.tax > 1
It is likely that the computation can be simplified, but it is hard to tell without an explanation of its purpose. Maybe something like this?
(o.total_margin / 1000 - COALESCE(p.tax, 0) * o.total_margin / 100000) / 1000 AS Profit

Related

Why is my average query showing incorrect values? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I asked a question a few hours ago that was marked as closed and referred me a link that did not clear up my confusion.
I am trying to query a sports database in MySQL to list the names of players who are above average age compared to their teammates. Ideally, I want to group by team, find the average of each team, and compare that to each respective player on that team.
My results from this query seem to be comparing players to the entire databases' average, rather than the average of the team. Can anyone correct my query or propose an alternate query to get the correct data? A friend of mine suggested perhaps using two copies of the tables, but that is beyond the scope of my limited MySQL skills.
My relational schema are as follows:
player(player_name, age, position)
plays_for (player_name, team_name)
SELECT player.player_name, player.age
FROM
plays_for
INNER JOIN player ON player.player_name=plays_for.player_name
WHERE (SELECT AVG(age) FROM player
GROUP BY plays_for.team_name1)< player.age
Your WHERE statement does not include the team grouping. I personally like WITH statements which seems to be the direction your friend was going.
> WITH average_ages AS ( SELECT AVG(p.age) AS average_age, pf.team_name
> FROM player p join plays_for pf on p.player_name = pf.player_name
> GROUP BY pf.team_name) aa
> SELECT player.player_name, player.age
> FROM plays_for
> INNER JOIN player ON player.player_name=plays_for.player_name
> INNER JOIN average_ages ON plays_for.team_name = average_ages.team_name
> WHERE player.age > average_ages.average_age;
The WITH statement at the top creates a temporary table of average ages and then joins it to the plays_for table.
The first few rows of the entire SELECT query before the WHERE statement would look like this
Name Age Team Average_age
Tara 51 KOs 25
Bomb 45 KOs 25
Jess 20 BES 30
Buster 40 BES 30

Trying to union these together but I can't figure out what it's telling me: Error converting data type varchar to bigint [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This is the code that I have going:
SELECT e.EncounterID, YEAR(e.EntryDate) AS 'Year', MONTH(e.EntryDate) AS 'Month', ac.Description AS 'PresentingProblem', c.ClinicName
FROM encounters AS e
JOIN clinics AS c
ON e.clinic = c.ClinicID
JOIN activitycodes AS ac
ON e.PresentingProblem = ac.ActivityCode
UNION
SELECT ec.Description, dc.Reason AS 'Discharge_Reason', a.Duration, a.ExtraTime, nc.Description AS 'No Show Code'
FROM encountercodes AS ec
JOIN dischargecodes AS dc
ON ec.EncounterCode = dc.DischargeCode
JOIN appointments AS a
ON dc.DischargeCode = a.DischargeCode
JOIN noshowcodes AS nc
ON a.NoShowCode = nc.NoShowCode
There are several problems.
Top select shows EncounterID, does that match with description from the second select? I doubt it.
Then you have Year matched up with reason. Also not good.
Then Month lined up with duration.
etc.
Just match up your types on your SELECT columns.
SELECT e.EncounterID, YEAR(e.EntryDate) AS 'Year', MONTH(e.EntryDate) AS 'Month', ac.Description AS 'PresentingProblem', c.ClinicName
SELECT ec.Description, dc.Reason AS 'Discharge_Reason', a.Duration, a.ExtraTime, nc.Description AS 'No Show Code'

Mysql query with pivot table and multiple joins [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a sales table, a sale_staff table, a staff table and an offices table.
We are selling properties, and I want to find out the numbers of sales per seller for X month and per office.
The pivot table looks like this
sale_id , staff_id , type
type can be either seller or lister, so I need a where clause for this.
The sales table has a FK to the offices table; office_id
What I have so far is this, its TOTALLY wrong I know, but that's why i'm here - i need to fix the sums and include the office name from the office table, so
select st.first_name, st.last_name, office, count(*) as sold
from sales s, sale_staff ss
left join staff st
on st.id = ss.staff_id
left join offices off
on off.id = s.office_id
where ss.`type` = 'lister' and
year(s.sale_date) = 2017 and
month(s.sale_date) = 12
group by st.id
Sales table is simply a property sale item, price, address, office_id.
Besides the error unknown column s.office_id, as I said, the sum value is incorrect anyway. I'm really not experienced enough to understand this level of relationship joins and aggregating, any pointers please.
Basically I would like to simply see a resultset like
staff(seller) , count , office
Mike , 12 , West
Jim , 7 , East
Fred , 3 , East
Edit: SQLFiddle in case that helps :) Will add some sample test data.
Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. Your problem is because of the scoping rules around commas.
I would recommend:
select st.first_name, st.last_name, o.office, count(*) as sold
from staff st left join
sale_staff ss
on st.id = ss.staff_id join
sales sa
on sa.sale_id = ss.sale_id join
offices o
on o.id = s.office_id
where ss.`type` = 'lister' and
s.sale_date >= '2017-12-01' and
s.sale_date < '2018-01-01'
group by st.first_name, st.last_name, o.office;
I think this has the join condition correctly laid out, but it is hard to be sure without sample data and desired results.
Notes:
left join is probably not necessary. If it is, you should probably be starting with the staff table (to keep all staff).
Qualify all column names.
The group by includes all the non-aggregated columns in the from. This is a good habit if you are learning SQL.
The date comparisons are direct, without the use of functions.

I have this query that is driving me crazy [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this damn query that I'm trying to figure out but it driving me totally crazy cause I can't find a way to start building it.
This is the table structure on which I will query data.
----------------------------------------------------------------------------
| id | id_user | id_game| id_question | user_answer | answer_time | points |
----------------------------------------------------------------------------
the table is called game_user_answers and I'm supposed to find the winner of a quiz game.
I have another table called games in which i store id game and the game_start_time.
If the answer has 0 points than the user didn't answer correctly.
Basically what I want to do is to get the id_user that has more points combined from all answers he's given and his last answers time is closest to the game_start_time.The game id and the game_start_time will be passed as parameters to the function in which the query will be executed so don't worry about them.
Please help me out.
This is not the answer, but the start point for you.
Here is sqlfiddle: http://sqlfiddle.com/#!9/197dd9/1
You should add more data into that fiddle.
After that use my query to see some results and play with that query until you get to the closest result of what you expect to get. And once you get to the point when you can't get your goal, come back with your fiddle and query prepared and ask community for the help again.
SELECT
g.*,
gua.*
FROM games g
LEFT JOIN game_user_answers gua
ON g.id = gua.id_game
AND gua.answer_time>g.game_start_time
AND points>0
WHERE g.id = 1
AND g.game_start_time = '2016-01-01 00:00:00'

Complex SQL Query (sum entries) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am wondering if something like this could be implemented in SQL query.
Let say I have these tables:
Table Orders
id tax
01 800
02 255
Table DetailOrders
id price itemName
01 700 Book
01 500 Umbrella
01 100 Jacket
02 1000 Piano
Basically single entry of one table Orders corresponds to multiple entries in DetailOrders.
Is there are any way to write SQL query that would return something like this:
id tax sum-price all-names
01 800 1300 Book, Umbrella, Jacket
02 255 1000 Piano
It would sum the price of items with the same id, and somehow merge the names of the items with same id.
Could something like this be achieved?
How about something like
SELECT o.id,
o.tax,
sum(od.price) sum_price,
group_concat(itemName) all_names
FROM Orders o INNER JOIN
DetailOrders do ON o.id = do.id
GROUP BY o.id,
o.tax
Have a look at GROUP_CONCAT(expr)
This function returns a string result with the concatenated non-NULL
values from a group. It returns NULL if there are no non-NULL values.
It isn't hard:
select
o.id, o.tax,
sum(d.price),
group_concat(d.itemName)
from
orders as o
inner join detailOrders as d on o.id = d.id
group by
o.id