0

How can I get, in a single SELECT query, a result from two tables, one of which contains SUM function ?

Table SALARY

EMPLOYEE AMOUNT
John 1000
Bob 2000
Phill 4000
John 500
Bob 1000
Bob 100

Table ADRESS

EMPLOYEE CITY
John LA
Bob NYC
Phill LA

Expected result:

EMPLOYEE CITY AMOUNT
John LA 1500
Bob NYC 3100
Phill LA 4000

I know how to get the sum of salaries:

select EMPLOYEE, SUM(AMOUNT) from SALARY group by EMPLOYEE 

But I don't know how to combine the result with the ADDRESS table.

I tried this :

select S.EMPLOYEE, SUM(S.AMOUNT), A.city from SALARY S, ADDRESS A 
group by S.EMPLOYEE

=> "not a GROUP BY expression: 'A.CITY' must be in group by clause"

So I added A.CITY in the group by clause :

select S.EMPLOYEE, SUM(S.AMOUNT), A.city from SALARY S, ADDRESS A group by S.EMPLOYEE, A.city

Which gave me this result :

EMPLOYEE SUM(AMOUNT) CITY
John 3000 LA
John 1500 NYC
Bob 3100 NYC
Phill 8000 LA
Bob 6200 LA
Phill 4000 NYC
3
  • Regarding editting the question, for some reason the tables need a blank line above them to render correctly in the question, but the "preview" shows the tables correctly without the additional blank line. I've edited the question and added the blank lines so they show up correctly. Commented Sep 29, 2022 at 15:12
  • 2
    You failed to supply a join criteria in your FROM clause. A good rule to follow is to never use a comma to separate tables in your FROM. Join then correctly: from SALARY S INNER JOIN ADDRESS A on S.Employee = A.Employee. Replace your FROM clause in your last SQL attempt and rerun. By using a comma and not supplying join conditions, you were having your database join every row in SALARY with every row in ADDRESS. Commented Sep 29, 2022 at 15:15
  • @JNevill And I get your point about never use separate tables in the FROM, but use a JOIN instead. Thanks again Commented Sep 29, 2022 at 15:28

2 Answers 2

1

select S.EMPLOYEE,A.City, SUM(S.AMOUNT) AS Amount from SALARY S JOIN Address A on S.EMPLOYEE = A.EMPLOYEE group by S.EMPLOYEE,A.City;

Sign up to request clarification or add additional context in comments.

Comments

0

try this?

select S.EMPLOYEE, SUM(S.AMOUNT), A.city from SALARY S join ADDRESS A on A.EMPLOYEE=S.EMPLOYEE group by S.EMPLOYEE, A.city

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.