MySQL, Using a Subquery to get Rank of Score - mysql

I am trying to find out where this particular player ranks among shooting guards in the NBA. I am using this post on stackoverflow for a guide.
I get the error "Invalid use of group function".
SELECT
first,
last,
team,
pos,
SUM(points) AS scoresum,
ROUND(AVG(points), 2) AS avgpoints,
(SELECT
COUNT(*)
FROM nbaboxscore AS bpnb
WHERE (bpnb.first, bpnb.last, SUM(bpnb.points)) >= (bpn.first, bpn.last, SUM(bpn.points))) AS rank
FROM nbaboxscore AS bpn
WHERE bpn.pos = 'SG'
AND bpn.date >= '2009-10-01'
AND FIRST = 'Joe'
AND LAST = 'Johnson'
GROUP BY bpn.first, bpn.last, bpn.team
ORDER BY scoresum DESC
I'm not exactly sure if it's possible this way?

Your subquery is wrong, you cannot use SUM without GROUP BY and in WHERE, so you have to use HAVING.
I let you check : http://dev.mysql.com/doc/refman/5.0/fr/select.html

Related

How to optimize a query that is a join of 2 very similar queries but with different aggregation

I have the following query:
SELECT OBJ_DESC_ERRORS.description, OBJ_DESC_ERRORS.object, OBJ_DESC_ERRORS.count_errors, OBJ_ERRORS.count_total FROM
(SELECT `metrics_event`.`description`, `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_errors` FROM `metrics_event`
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`)
WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) )
GROUP BY `metrics_event`.`description`, `metrics_event`.`object` ORDER BY `count_errors` DESC ) as OBJ_DESC_ERRORS
JOIN
(SELECT `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_total` FROM `metrics_event`
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`)
WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) )
GROUP BY `metrics_event`.`object` ORDER BY `count_total` DESC ) as OBJ_ERRORS
ON OBJ_DESC_ERRORS.object = OBJ_ERRORS.object
which produces the following result:
As you can see I'm basically running the same query twice. The reason for that is that I need to have that count_errors broken down by each aggregation of object + description, but I also need the count_total to be only aggregated by object. This was the way I could think of. Now I'd like to know if this is the best I can do or if it can be optimized even further.
If so I have no clue how. Googling and searching similar topics on this is difficult because the optimization task depends on the query itself, so keywords here didn't help me much.
Get rid of the inner ORDER BYs; they do nothing useful.
Rewrite the query something like this:
SELECT
me.description,
me.object,
SUM(...) AS count_errors,
SUM(...) AS count_total
FROM `metrics_event` AS me
INNER JOIN `metrics_session` AS ms ON (me.`session_id` = ms.`id`)
WHERE ms.`training_id` = 4
ms.`completed_at` IS NOT NULL
GROUP BY me.`description`, me.`object`
ORDER BY `count_total` DESC
Since a boolean expression evaluates as 1 for TRUE, else 0, devise the argument to SUM() to be a boolean expression that provides the desired COUNT.

ORA-00979: not a GROUP BY expression error

Keep getting this error when everything from my select is in my group by statement as far as I can see
SELECT DISTINCT Case_Client_ID, Case_Client_Forename, Case_Client_Surname, SUM(Hours_Spent*Rate_Price_Per_Hour) AS
Money_Paid
FROM Case_Client, Legal_Case, Note, Rate
WHERE Case_Client.Case_Client_ID = Legal_Case.FK_Case_Client_ID
AND Legal_Case.Legal_Case_ID = Note.FK_Legal_Case_ID
AND Rate.Rate_ID = Note.FK_Rate_ID
GROUP BY Case_Client_ID, Case_Client_Forename, Case_Client_Surname
HAVING ROWNUM<=(SELECT COUNT(*)FROM Case_Client)/4
ORDER BY Money_Paid DESC;
Assuming Oracle and not MySQL, both are tagged.
The problem is rownum in the having clause. Rownum will have multiple values for a single group.
I am unclear what you are attempting to do, so I don't have a fix to suggest.

Refine Query Results from MySQL Database

I have the following query:
SELECT routes.route_date, time_slots.name, time_slots.openings, time_slots.appointments
FROM routes
INNER JOIN time_slots ON routes.route_id = time_slots.route_id
WHERE route_date
BETWEEN 20140109
AND 20140115
AND time_slots.openings > time_slots.appointments
ORDER BY route_date, name
This works just fine and will produce the following results:
What I want to do is only return one name per date. So the 9th, name = 1, would only have 1 result, rather than 2, as it currently does.
UPDATE: See the SQLFIDDLE for different type of solutions here: http://sqlfiddle.com/#!2/9ac65b/6
Will it solve your request if you use...
SELECT DISTINCT routes.route_date...your query... ?
It depends if you know that your rows always will have the same values, for same date/name.
Otherwise use group by...
(which I think suits your request best)
SELECT routes.route_date, time_slots.name, sum(time_slots.openings), sum(time_slots.appointments)
FROM routes
INNER JOIN time_slots ON routes.route_id = time_slots.route_id
WHERE route_date
BETWEEN 20140109
AND 20140115
AND time_slots.openings > time_slots.appointments
group by routes.route_date, time_slots.name
ORDER BY route_date, name
(i did a sum for the openings and appointments, you could do min, max, count, etc. Pick the one that fits your requirements best!)
You need to figure out which "name" you want when there are several for the same date.
Then you can group by date and select the right "name" by using an aggregate function like COUNT, MAX, etc.
I can't help you more if you don't explain your rule for picking one.

Operand should contain 1 column(s) when selecting data from another table AS value

Can some one please help me here, ive Googled, and looked at other examples with this error but it just confuses me and i cant seem to get my head around this.
im struggling with selecting data AS something else in a mysql query im getting the following error...
Operand should contain 1 column(s)
What is an simplified term for an Operand?
below is the mysql query...
SELECT atable_garage.id,
atable_garage.total_votes as num_votes,
atable_garage.name,
atable_garage.address,
atable_garage.city,
atable_garage.postcode,
atable_garage.main_dealer,
atable_garage.phone,
atable_garage.website,
atable_garage.description,
atable_garage.years_in_business,
atable_garage.garage_image,
(SELECT(avg(quality_of_repair) + avg(attitude_of_staff) + avg(overall_satisfaction))/3 as rating,
count(*) as num_votes
FROM atable_feedback
WHERE validated = 'Y'
AND atable_garage.id = garage_id)
FROM `atable_garage`
WHERE valeting = 'Y'
AND active = 'Y'
ORDER BY rating DESC, atable_garage.total_votes DESC
Can anyone point out what I've done wrong here? and if possible explain I'm finding it difficult to get my head around this one thanks in advance.
The correlated subquery can only return one column at a time. Since you want to have two column, you can restrusture the query by converting it into LEFT JOIN.
SELECT atable_garage.id,
atable_garage.total_votes as num_votes,
atable_garage.name,
atable_garage.address,
atable_garage.city,
atable_garage.postcode,
atable_garage.main_dealer,
atable_garage.phone,
atable_garage.website,
atable_garage.description,
atable_garage.years_in_business,
atable_garage.garage_image,
COALESCE(b.rating, 0) rating,
COALESCE(b.num_votes, 0) num_votes
FROM atable_garage
LEFT JOIN
(
SELECT garage_id,
(avg(quality_of_repair) + avg(attitude_of_staff) + avg(overall_satisfaction)) / 3.0 as rating,
count(*) as num_votes
FROM atable_feedback
WHERE validated = 'Y'
GROUP BY garage_id
) b ON atable_garage.id = b.garage_id
WHERE valeting = 'Y' AND active = 'Y'
ORDER BY rating DESC,
atable_garage.total_votes DESC
When using a sub-select for a column, you can only return one value, like this:
(SELECT avg(quality_of_repair) + avg(attitude_of_staff) + avg(overall_satisfaction)
FROM atable_feedback
WHERE validated = 'Y'
AND garage_id = atable_garage.id
)/3 as rating,

PGError: ERROR: column "inboxes.id" must appear in the GROUP BY clause or be used in an aggregate function

I have the following query to MySQL database:
SELECT inboxes.*
, count(inboxes.conv) AS times
, max(created_at) AS created_at
FROM `inboxes`
WHERE to_user = 2
OR account_id = 2
GROUP BY conv
ORDER BY id DESC
This query works on my localhost, but if I deploy it to Heroku, I'll get this error:
PGError: ERROR: column "inboxes.id" must appear in the GROUP BY clause or
be used in an aggregate function
You need to specify all fields in GROUP BY, which you wanna select, ie:
SELECT inboxes.id, count(inboxes.conv) AS times, max(created_at) as created_at FROMinboxesWHERE (to_user = 2 OR account_id = 2) GROUP BY inboxes.id, conv ORDER BY inboxes.id DESC
To avoid problems like this in the future, install postgres locally and develop your application with the same database it is using in production.
You should get rid of the inboxes.*. List each single parameter you need to fetch.
All parameters must be either grouped (GROUP BY) or used together with a group function(MAX, etc.).
I cannot tell you why its working on your localhost.