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
Related
I have an events executed table wherein I want to separate columns based on the dates
SELECT Event_ID,Name,count(Customer_Id) FROM UNLIMITED.Event_Execution a
join UNLIMITED.Event_Master b on a.Event_Id=b.ID
Where Event_Execution_Date_ID = '20211007'
group by Event_Id
order by Count(Customer_Id) desc;
Desired output
Event_ID Name 20211006 20211007
1 Offer1 1,218 6,876
2 Offer2 10,212 4,123
You want conditional aggregation:
select
event_id,
name,
count(case when event_execution_date_id = '20211006' then customer_id end) as cnt_20211006,
count(case when event_execution_date_id = '20211007' then customer_id end) as cnt_20211007
from unlimited.event_execution a
join unlimited.event_master b on a.event_id = b.id
where event_execution_date_id in ('20211006', '20211007')
group by event_id
order by count(customer_id) desc;
Side notes:
a and b are bad alias names. use something mnemonic, e.g. e for the execution table and m for the master table.
When working with several tables, qualify all columns. Which table does customer_id belong to for instance?
Why count(customer_id)? Is customer ID a nullable column? Or does it reside in the execution table and you want to be able to outer join this table at some time and get the correct count of zero? Or what is the reason to count an expression and not just rows (count(*))?
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.
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.
I have 2 tables joined by the membership.ID and memberDues.memberID. The membership table has a column, firstLast, which is unique for each row. If I have a value for firstLast, i should be able to then find the membership.ID and compare it to the memberDues.memberID. I am using the following query but it doesn't work:
SELECT * FROM memberDues, membership
WHERE memberID =
( SELECT ID FROM membership
WHERE firstLast = 'Jim Smith')
ORDER BY payDate DESC
LIMIT 1
The result gets the correct memberDues.memberID and the other data from its row but pulls an unrelated data set from the membership table where even the ID is wrong. What's wrong with the query?
You can join the two tables on their shared ID values and then you can select only those rows which have firstLast = 'Jim Smith'. I think you can achieve more efficiently what you want (avoiding one additional select) using the following query:
SELECT aa.*, bb.*
FROM memberDues AS aa
INNER JOIN membership AS bb
ON aa.memberID = bb.ID
WHERE bb.firstLast = 'Jim Smith'
ORDER BY aa.payDate DESC
LIMIT 1;
You should use IN instead of equal sign:
SELECT * FROM memberDues, membership WHERE memberID IN
(SELECT ID FROM membership WHERE firstLast = 'Jim Smith')
ORDER BY payDate DESC LIMIT 1
What's wrong with the query?
Your query joins 2 tables without specifying a condition to relate them.
For a fast start on your question, I'd try to specify
membership.ID = memberDues.memberID in the where clause.
My personal advice is to use a LEFT JOIN using that condition in the ON clause. But it's more advanced SQL coding, and choices depends on the structure and the needs of this particular application.
I'm running two queries.
The first one gets unique IDs. This executes in ~350ms.
select parent_id
from duns_match_sealed_air_072815
group by duns_number
Then I paste those IDs into this second query. With >10k ids pasted in, it also executes in about ~350ms.
select term, count(*) as count
from companies, business_types, business_types_to_companies
where
business_types.id = business_types_to_companies.term_id
and companies.id = business_types_to_companies.company_id
and raw_score > 25
and diversity = 1
and company_id in (paste,ten,thousand,ids,here)
group by term
order by count desc;
When I combine these queries into one it takes a long time to execute. I don't know how long because I stopped it after minutes.
select term, count(*) as count
from companies, business_types, business_types_to_companies
where
business_types.id = business_types_to_companies.term_id
and companies.id = business_types_to_companies.company_id
and raw_score > 25
and diversity = 1
and company_id in (
select parent_id
from duns_match_sealed_air_072815
group by duns_number
)
group by term
order by count desc;
What is going on?
It's down to the way it processes the query - I believe it has to run your embedded query once for each row, whereas using two queries allows you to store the result.
Hope this helps!
The query has been re-written using JOIN, but particularly I've used EXISTS instead of IN. This is a short in the dark. It is possible that there may be many values generated in the sub-query causing the outer query to struggle while it goes through matching each item returned from the sub-query.
select term, count(*) as count
from companies c
inner join business_types_to_companies bc on bc.company_id = c.id
inner join business_types b on b.id = bc.term_id
where
raw_score > 25
and diversity = 1
and exists (
select 1
from duns_match_sealed_air_072815
where parent_id = c.id
)
group by term
order by count desc;
First, with respect, your subquery doesn't use GROUP BY in a sensible way.
select parent_id /* wrong GROUP BY */
from duns_match_sealed_air_072815
group by duns_number
In fact, it misuses the pernicious MySQL extension to GROUP BY. Read this. http://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html . I can't tell what your application logic intends from this query, but I can tell you that it actually returns an unpredictably selected parent_id value associated with each distinct duns_number value.
Do you want
select MIN(parent_id) parent_id
from duns_match_sealed_air_072815
group by duns_number
or something like that? That one selects the lowest parent ID associated with each given number.
Sometimes MySQL has a hard time optimizing the WHERE .... IN () query pattern. Try a join instead. Like this:
select term, count(*) as count
from companies
join (
select MIN(parent_id) parent_id
from duns_match_sealed_air_072815
group by duns_number
) idlist ON companies.id = idlist.parent_id
join business_types_to_companies ON companies.id = business_types_to_companies.company_id
join business_types ON business_types.id = business_types_to_companies.term_id
where raw_score > 25
and diversity = 1
group by term
order by count desc
To optimize this further we'll need to see the table definitions and the output from EXPLAIN.