简体   繁体   中英

SQL : SQL query to fetch the corresponding data

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'.

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

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM