1

I have 2 select statements pulling data from 2 tables for the same people. I know they can be combined via a join, but I can't get the syntax to work for me.

Query 1:

SELECT SUBSTRING_INDEX(username,'@',1) AS username, 
COUNT(username) as count,
ROUND(
SUM(
CONVERT(SUBSTRING(contribution_score, -2), UNSIGNED INTEGER)  +
CONVERT(SUBSTRING(focused_score, -2), UNSIGNED INTEGER)  +
CONVERT(SUBSTRING(prepared_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(work_score, -2), UNSIGNED INTEGER)  
)/COUNT(username)/76*100)
as average

FROM project_rubrics
GROUP BY username
LIMIT 0, 90

Query 2:

SELECT username,COUNT(username) as days FROM logon GROUP BY username

The common link is the username field.
I'd like one result set that gives the username, days, and average for each student, but I can't get joins or combined selects to work.

Any help is appreciated.

2
  • the UNION keyword is what your looking for see mysqltutorial.org/sql-union-mysql.aspx
    – DragonZero
    Mar 26, 2013 at 20:49
  • Union won't work unless he changes the column name of the second second query and in this case would create two rows per username.
    – Robbert
    Mar 26, 2013 at 21:01

1 Answer 1

0

You could do a subquery.

SELECT SUBSTRING_INDEX(username,'@',1) AS username, 
COUNT(username) as count,
ROUND(
SUM(
CONVERT(SUBSTRING(contribution_score, -2), UNSIGNED INTEGER)  +
CONVERT(SUBSTRING(focused_score, -2), UNSIGNED INTEGER)  +
CONVERT(SUBSTRING(prepared_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(work_score, -2), UNSIGNED INTEGER)  
)/COUNT(username)/76*100)
as average,

(SELECT COUNT(username) as days FROM logon WHERE logon.username=project_rubrics.username GROUP BY username) as username_count

FROM project_rubrics
GROUP BY username
LIMIT 0, 90
2
  • Unfortunately, that didn't work. It returned an error that more than 1 row as returned by the subquery. Mar 27, 2013 at 9:58
  • This works for me (different database, but same general idea). Maybe your group by statement in the subquery should specify the table: SELECT COUNT(username) as days FROM logon WHERE logon.username=project_rubrics.username GROUP BY logon.username.
    – Robbert
    Mar 27, 2013 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.