0

So, the problem is that I need to find the the total number of gifts received by the people with the nationality 'America', Now I have 2 different tables named gift_info and users_info, the users_info table contains the nationality attribute while the gift_info contains the gift_id attribute.

I have come up with something like

SELECT users_info.user_id, gift_info.gift_id, users_info.nationality
FROM gift_info
LEFT JOIN users_info
ON  gift_info.gift_id = users_info.user_id
where users_info.nationality = 'America'

the output this query gives is the user_id, the gift_id and the nationalities 'America' while I need the the total number of gifts recived by people of nationality 'America'.

2
  • 1
    Is this condition ON gift_info.gift_id = users_info.user_id correct ? Commented Aug 23, 2020 at 22:17
  • Now that I think of it, it doesn't make sense, thanks for pointing it out! Commented Aug 23, 2020 at 22:49

2 Answers 2

1

Modify the SELECT statement to Count the number of gift IDs and add a GROUP BY clause:

SELECT COUNT(DISTINCT gift_info.gift_id)
FROM gift_info
LEFT JOIN users_info
ON  gift_info.user_id= users_info.user_id    
where users_info.nationality = 'America'
GROUP BY users_info.nationality = 'America'

Edited WHERE clause per @Sujitmohanty30's comment

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

Comments

0

If I understand correctly, I think you want:

SELECT COUNT(*)
FROM gift_info gi JOIN
     users_info ui
     ON gi.user_id = ui.user_id
WHERE ui.nationality = 'America';

Notes:

  • An outer join is not appropriate because you need the nationality.
  • Table aliases make the query easier to write and to read.
  • I think a simple COUNT(*) suffices to get the number of gives. If you want the number of people, use COUNT(DISTINCT ui.user_id).

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.