Giving a result with a sub query and a formula? - mysql

I have this issue that is going around my head lately, I wanna know how many of my users can have more than a 50% of profit in their accounts. So, as you can see in the table, I have investment and earnings, so logically I must do a percentage for having the profit. Like: ((earnings - investment * 100) / investment)
ID Investment (euros) Earnings (euros)
13 2 3.4
14 1 0
15 4 7
16 12 20.76
From here everything is ok, but my question is, how can I calculate and show at the same time the users that have more than a 50% of profit?
I made this simple query that works but don't shows the users that have more than 50%, shows everyone.
select id, ((MAX(earnings)-investment)*100)/investment
from users
group by id, investment
;
So, my idea was to create a subquery, but I have a great issue with this:
select id
from users
where 50 < (
select (((MAX(earnings)-investment)*100)/investment)
from users
group by investment
)
group by id
;
I received this error:
Detail: Expected no more than one row to be returned by expression
I don't know what I'm doing wrong. Jalp!

Isn't this the formula?
select id, (sum(earnings) - sum(investment))*100 / sum(investment) as profit
from users
group by id;
Then if you want to filter, add:
having profit > 50
To get the count, use a subquery:
select count(*)
from (select id, (sum(earnings) - sum(investment))*100 / sum(investment) as profit
from users
group by id
) u
where profit > 50;

Related

Calculating Value Count and Percentage

I have a table
Currently Enrolled
The table is basically to get an idea of how many supporters, undecided, and opposition they were. Then once I get the count I wanted to then do another calculation to find out what that percentage was.
Essentially what I want to be able to do is:
Count the total number of supporters:
SELECT count(*) AS 'SUPPORTERS' FROM CURRENTLY ENROLLED WHERE
status = 'Supporter'
results were 13
Count the total number of opposition:
SELECT count(*) AS 'OPPOSITION' FROM CURRENTLY ENROLLED WHERE value = 'Opposition'
results were 11
Count the total number of undecided persons using a similar statement:
SELECT count(*) AS 'UNDECIDED' FROM CURRENTLY ENROLLED WHERE value = 'Undecided'
results were 5
So with the count, I can see that they're 29 total individuals. I wanted to be able to get the percentage of each of them separately. Something like
13/29 * 100 = 44%
11/29 * 100 = 37%
5/29 * 100 = 17%
However, I am lost on how to write this query.
Hope I am making this clear as to the intentions.
Use a CTE for the total and group by status for the percentage:
with cte as (select count(*) as cnt from `currently enrolled`)
select status, sum(100)/cnt
from `currently enrolled`, cte
group by 1

Unique MySQL query

I really am struggling with a MySQL query, I have a table named 'info' and in it I have a column called 'rating' in it I have ratings between 1-10.
Now I need to generate a percentage value of how many ratings are from 1-6 and 7-8 and 9-10 but I need them to display desperately and after that I need a second query that can subtract the percentage value of the results from 1-6 and 9-10.
The query below is as close as I could get from all my research however I don't know how to get a percentage of ratings 1-6 only and not all of them and also how to get a second query to subtract the 1-6 and 9-10 rating percentages. Any help would be amazing.
SELECT rating,
COUNT(*) AS Count,
(COUNT(*) / _total ) * 100 AS Percentege
FROM info,
(SELECT COUNT(*) AS _total FROM info) AS myTotal
GROUP BY rating
Try this:
select if(rating between 1 and 6, '1-6',
if( rating between 7 and 8, '7-8',
'9-10' )
) as rating_range,
count(1) as num
from info
group by rating_range
fiddle code

SQL: Select count and percentage with conditions

I have two tables
User
id_user|INT
company | varchar
and
Log
log_id|int
id_user|int
I need to return the company, the total number of users per company, and the percentage of users that have atleast 3 logs
I can run this query to get the company and counts
select company, count (*) as 'Count'
from user
group by company
which returns this
Apple| 7
Google| 6
But I am having trouble figuring out how to then return an extra column that displays the percentage of those users that have at least 3 logs. For example,
If there were 2 users who had more than 3 logs from Apple and one user from Google who had more than 3 logs, the answer would look like this:
Apple| 7| 29% (because 2/7=~29%)
Google| 6| 17% (because 1/7=~17%)
I figured this requires the use of windows function or some type of correlated subquery but I'm having issues accurately obtaining the correct percentage.
Any help would be greatly appreciated. (using SQL server 2008)
I was actually able to do this without using window functions, though there is probably a version which would use them. First, I aggregate the number of logs per user in a CTE. Then, I join the user table to this, using conditional aggregation to count the number of users per company having 3 logs or more.
WITH cte AS (
SELECT id_user, COUNT(*) AS cnt
FROM Log
GROUP BY id_user
)
SELECT
u.company,
COUNT(DISTINCT u.id_user) AS total_users,
100.0 * SUM(CASE WHEN c.cnt >= 3 THEN 1 ELSE 0 END) /
COUNT(DISTINCT u.id_user) AS log_3_users
FROM [User] u
LEFT JOIN cte c
ON u.id_user = c.id_user
GROUP BY
u.company;
Demo
Note that in the demo I just have some dummy data, where 1 out of 3 Google users has 3 or more logs, and 1 out of 2 Microsoft employees has 3 or more logs.

Percent of records with a single MySQL Query

Say I have a table users with columns user_id, name, rate. I want to get % positive rating. The formula for this is:
((all records with rating >= 3) / (total records)) * 100
This can be done by getting total records and all records with rating >= 3 by two queries. But I want to get this done using only one query. How can I do this?
select sum(rate >= 3) * 100 / count(*)
from users

MySQL - Calculating Net Dues against two tables

Thanks in advance for any assistance. I am new to SQL and have looked at several related threads on this site, and numerous other sites on Google, but have not been able to figure out what I am doing wrong. I have looked at sub-selects, various JOIN options, and keeping bumping into the wrong solution/result.
I have two tables that I am trying to do a query on.
Table:Doctors
idDoctors
PracticeID
FirstName
LastName
Table: Vendor Sales
Id
ProductSales
SalesCommission
DoctorFirstName
DoctorLastName
Here is the Query I am struggling with:
SELECT t1.PracticeID
, SUM( t2.ProductSales ) AS Total_Sales
, COUNT( t1.LastName ) AS Doctor_Count
, COUNT( t1.LastName ) *150 AS Dues
, SUM( t2.ProductSales * t2.SalesCommission ) AS Credit
FROM Doctors AS t1
JOIN VendorSales AS t2 ON t1.Lastname = t2.DoctorLastName
GROUP BY t1.PracticeID
LIMIT 0 , 30
The objective of the Query is to calculate net dues owed by a Practice. I am not yet attempting to calculate the net amount, just trying to get the initial calculations correct.
Result (limited to one result for this example)
PracticeID Total_Sales Doctor_Count Dues Credit
Practice A 16583.04 4 600 304.07360
This is what the result should be:
PracticeID Total_Sales Doctor_Count Dues Credit
Practice A 16583.04 3 450 304.07360
The problem is that Total Sales sums the aggregate sales transactions (in this case 4 sales entries totaling 16584.04). Each of the 4 sales has an associated commission rate. The Credit amount is the total (sum) of the commission.
The sales and credit numbers are accurate. But the Doctor count should be 3 (number of Doctors in the practice). Dues should be $450 (150x3). But as you can see it is multiplying by 4 instead of 3.
What do I need to change in the query to get the proper calculations (Doctors and dues multiplied by 3 instead of 4? Or should I be doing this differently? Thanks again.
There are various odd things about your schema, and you have not provided the sample data to justify your asserted values.
The first oddity is that you have both first and last name for the doctor in the Doctors table, and in the Vendor Sales table - yet you join only on the last name. Next, you have an ID column, it seems, in the Doctors table, yet you do not use that in the Vendor Sales table for the joining column.
It is not clear whether there is one entry in the Vendor Sales table per doctor, or whether there can be several. Given the counting issues you describe, we must assume there can be several entries per doctor in the Vendor Sales table. It also isn't clear where the vendor is identified, but we have to assume that is not germane to the problem.
So, one set of data you need is the number of doctors per practice, and the dues (which is 150 currency units per doctor). Let's deal with that first:
SELECT PracticeID, COUNT(*) AS NumDoctors, COUNT(*) * 150 AS Dues
FROM Doctors
GROUP BY PracticeID
Then we need the total sales per practice, and the credit too:
SELECT t1.PracticeID, SUM(t2.ProductSales) AS Total_Sales,
SUM(t2.ProductSales * t2.SalesCommission) AS Credit
FROM Doctors AS t1
JOIN VendorSales AS t2 ON t1.Lastname = t2.DoctorLastName
GROUP BY t1.PracticeID
These two partial answers need to be joined on the PracticeID to produce your final result:
SELECT r1.PracticeID, r1.NumDoctors, r1.Dues,
r2.Total_Sales, r2. Credit
FROM (SELECT PracticeID, COUNT(*) AS NumDoctors, COUNT(*) * 150 AS Dues
FROM Doctors
GROUP BY PracticeID) AS r1
JOIN (SELECT t1.PracticeID, SUM(t2.ProductSales) AS Total_Sales,
SUM(t2.ProductSales * t2.SalesCommission) AS Credit
FROM Doctors AS t1
JOIN VendorSales AS t2 ON t1.Lastname = t2.DoctorLastName
GROUP BY t1.PracticeID) AS r2
ON r1.PracticeID = r2.PracticeID;
That should get you the result you seek, I believe. But it is untested SQL - not least because you didn't give us appropriate sample data to work with.