MySQL Values Relying on Different Tables - mysql

In this database:
I need to write an SQL query that will display the name of each client of the agent with the highest agent rating in the company.
What I'm trying right now is,
SELECT ClientName
FROM CLIENT.ClientName
WHERE CLIENT.AgentID = AGENT.AgentID AND MAX(AGENT.AgentRating);
I'm new to MySQL, so I just want to check if I'm using the MAX and AND operators properly, or if there's a simpler way to do this.

Try using a subquery to select the highest rated agent, then join it to your CLIENT table to select the names of the associated clients. Something like this:
SELECT ClientName
FROM CLIENT.ClientName
JOIN (
SELECT AgentID FROM AGENT ORDER BY AgentRating DESC LIMIT 1
) sq ON sq.AgentID = CLIENT.AgentID
The subquery (SELECT AgentID FROM AGENT ORDER BY AgentRating DESC LIMIT 1) sq selects the AgentID column from the AGENT table
Then with ORDER BY AgentRating DESC it orders that column by the AgentRating descending placing the highest rating at the top of the results.
Then the LIMIT 1 limits the rows returned to 1, giving you only 1 (the first returned) record from the AGENT table that we just ordered to put the highest rated agent at the top.
Then when you JOIN that result from the subquery with your CLIENT table on the AgentID, you will only get results in your CLIENT table maching the selected AgentID from the subquery.

Related

Using JOIN in sql for two derived tables

Basically, I have two separate queries, which I need to somehow merge into one set of results.
![This is Table 1, which shows the sum of each group's salary]
1
Here is the queries I wrote to form the tables.
SELECT con_stagename, SUM(p_daily_salary) AS sum_salary
FROM CONTENDER, PARTICIPANT
WHERE p_contender = con_id
GROUP BY con_id;
SELECT MAX(sum_salary) AS max_salary
FROM (SELECT con_stagename, SUM(p_daily_salary) AS sum_salary
FROM CONTENDER, PARTICIPANT
WHERE p_contender = con_id
GROUP BY con_id) T2;
And the question is, if I want the result to be a single row of values, which the name of the group with the highest salary, and the actual amount. How would I do it? I've been trying to use JOIN operations but there was not luck.
SELECT con_stagename, SUM(p_daily_salary) AS sum_salary
FROM CONTENDER, PARTICIPANT
WHERE p_contender = con_id
GROUP BY con_id
ORDER BY 2 DESC
LIMIT 1

SQL Ordering rows in a select with multiple conditions

I am trying to create an SQL Query to select rows from a database, ordered by a numerical field, however there are repeated entries in the table.
The table consists of the following columns.
UID - Numerical Unique ID
ACCOUNT_NAME - Account Name, unchanged
NICK_NAME - Can be changed by the user at any time
POINTS - Records points held by the user's account
The goal of the query is to display the Account_Name ordered by Points. However, Account_Name is not unique and can appear multiple times in the table.
To deal with this I would like to display only the latest row for each Account_Name.
This meaning that in the results from the select each Account_Name should only appear once. I am trying to have the selection be decided by the UID, meaning that I want only the row with the greatest UID where each account_name appears to be displayed.
I have tried the following without desired results. (The name of the table is ACCOUNT)
SELECT DISTINCT A.account_name , A.uid, A.points
FROM account A, account B
where A.account_name = B.account_name
and A.points > 0
and A.uid >= B.uid
order by A.points DESC;
This doesn't give me the desired results, specifically, there is an account in the database where an outdated row exists with a high value in the Points column. This record appears as the first result in the select, even though it is outdated.
How would you recommend adjusting this Query to select the desired information?
I hope this is enough information to work off of (first time posting a question) Thank you for you help :)
EDIT: Adding in examples with data.
Sample Table Data:
Sample Table Data
Current Results:
Current Results
Desired Results:
Desired Results
Consider joining on an aggregate query calculating MAX(UID)
SELECT a.account_name, a.uid, a.points
FROM account a
INNER JOIN
(
SELECT account_name, MAX(uid) AS max_uid
FROM account
GROUP BY account_name
) agg
ON a.account_name = agg.account_name
AND a.uid = agg.max_uid)
WHERE a.points > 0
ORDER by a.points DESC;
Alternatively, with MySQL 8.0, consider a window function:
SELECT a.account_name, a.uid, a.points
FROM account a
WHERE a.points > 0
AND a.uid = MAX(a.uid) OVER (PARTITION BY a.account_name)
ORDER by a.points DESC;

JOIN, ORDER BY and GROUP BY in same statement

I have two tables - results and contestants. Result table cointains
result_id (PK)
resul_contestant (who scored this)
value (how much did he scored)
result_discipline(where he scored this)
contestants table cointains
contestant_id (PK)
contestant_name
contestant_category
What I want to do is to select results for all contestants, but I only want to show one result per contestant - the highest (lowest) one.
So far I managed to do this:
SELECT * FROM contenstants
JOIN results ON result_contestant = contenstant_id
WHERE result_discipline = 1 AND contestant_category = 1
ORDER BY value DESC
GROUP BY contenstant_id;
However, this gives me syntax error. If I delete the GROUP BY line, I got results ordered from highest, but if any of the contestants scored in this discipline more than once, I got all of his scores.
If I delete the ORDER BY line, I got only one result per contestant, but it returns the first record in db, not the highest one.
How to fix this command to be valid? Also, there are some less_is_better disciplines, where I want the lowest score, but as far as I could use the ORDER BY on final query, it should be achieved by replacing DESC with ASC.
Thanks.
Don't use group by. Using select * with group by just doesn't make sense. Instead, use a filter to get the row you want:
SELECT *
FROM contenstants c JOIN
results r
ON r.result_contestant = c.contestant_id
WHERE r.result_discipline = 1 AND c.contestant_category = 1 AND
r.value = (select min(r2.value)
from results r2
where r2.result_contestant = r.result_contestant and
r2.result_discipline = r.result_discipline
)
ORDER BY value DESC;
Note: I'm not sure if you want min() or max() in the subquery.

What is the use of bet.user.id, users.user_name, and users.user_status after FROM in this SQL query?

I have the following query that I am using to get the sum of values from a database so as to rank each individual user. The table does not return total sum but sum of each balance_return for each user who is verified.
SELECT SUM( bets.balance_return )
AS total_wins, bets.user_id, user.username, user.status
FROM bets
INNER JOIN user ON bets.user_id = user.id
WHERE user.status = 'verified'
GROUP BY bets.user_id
ORDER BY total_wins DESC
LIMIT 0 , 10
My results return a list of 10 users with their individual sum of balance_return and they are ranked from the highest to the lowest. The columns returned are total_wins user_id username and status. I needed to know how the result is taking every row on bets table with a unique user_id , adding the total of balance_return and finally giving ranking according to the sum. Going through the query, I do not see how this is being done.

MYSQL Limit Occurences of a particular column value

Pulling some coupons from a database. Each coupon has a merchantid column that contains the id for the merchant for which the coupon belongs too.
I'm trying to construct a query that pulls 5 coupons, but I only want 1 coupon per merchantid. I don't want multiple coupons with the same merchantid.
You could use
SELECT * FROM coupons GROUP BY merchantid LIMIT 0,5;
And it will work because
MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause (see docs)
If you don't want MySQL to decide which merchantid to keep, you can add your condition
(in example below - keep merchant with highest number of clicks) using subquery:
FIXED:
SELECT c1.*
FROM coupons c1 JOIN (
SELECT t.merchantid, MAX(t.numberofclicks) maxnumberofclicks
FROM coupons t GROUP BY t.merchantid
) c2 ON c1.merchantid = c2.merchantid AND c1.numberofclicks = c2.maxnumberofclicks
LIMIT 0,5;
And one more (more concise and probably faster on large datasets) way to skin a cat:
SELECT c1.*
FROM coupons c1 JOIN coupons c2 ON c1.merchantid = c2.merchantid
GROUP BY c1.merchantid, c1.numberofclicks
HAVING c1.numberofclicks = MAX(c2.numberofclicks)
LIMIT 0,5;
If you want 5 coupons with overall highest number of clicks, add ORDER BY c1.numberofclicks DESC before LIMIT 0,5.
try
SELECT * FROM your_table_name GROUP BY merchantid LIMIT 0,5;
this would give 5 rows which has distinct merchantid's, but you may get the same result for different executions. if you want to randomize it, randomize 'A' inside 'LIMIT A,5'.