Jump to content

Counting data from 2 tables


JohnL

Recommended Posts

I have two tables: USERS and PICTURES

Sample data for USERS:
[table]
[tr][td]id[/td][td]birth_date[/td][/tr]
[tr][td]1[/td][td]1970-01-01[/td][/tr]
[tr][td]2[/td][td]1987-01-01[/td][/tr]
[tr][td]3[/td][td]1980-01-01[/td][/tr]
[tr][td]4[/td][td]1981-01-25[/td][/tr]
[tr][td]5[/td][td]1982-07-01[/td][/tr]
[tr][td]6[/td][td]1985-01-25[/td][/tr]
[tr][td]7[/td][td]1978-07-01[/td][/tr]
[tr][td]8[/td][td]1970-01-01[/td][/tr]
[/table]

Sample data for PICTURES
[table]
[tr][td]id[/td][td]pictureNo[/td][/tr]
[tr][td]1[/td][td]1[/td][/tr]
[tr][td]1[/td][td]2[/td][/tr]
[tr][td]1[/td][td]3[/td][/tr]
[tr][td]7[/td][td]1[/td][/tr]
[tr][td]7[/td][td]2[/td][/tr]
[/table]

The following query
SELECT floor(period_diff(extract(year_month from NOW()),extract(year_month from birth_date))/12) as age, count(*) FROM db.USERS u group by age order by age;

Would return
[table]
[tr][td]age[/td][td]count(*)[/td][/tr]
[tr][td]20[/td][td]1[/td][/tr]
[tr][td]22[/td][td]1[/td][/tr]
[tr][td]24[/td][td]1[/td][/tr]
[tr][td]26[/td][td]1[/td][/tr]
[tr][td]27[/td][td]1[/td][/tr]
[tr][td]28[/td][td]1[/td][/tr]
[tr][td]37[/td][td]2[/td][/tr]
[/table]

This is half my Job done. I do not know how to go about doing the next task which is to count how many users has uploaded at least one picture within that age group.

What query is required to return a result looking something like
[table]
[tr][td]age[/td][td]age count(*)[/td][td]pictures count(*)[/td][/tr]
[tr][td]20[/td][td]1[/td][td]0[/td][/tr]
[tr][td]22[/td][td]1[/td][td]0[/td][/tr]
[tr][td]24[/td][td]1[/td][td]0[/td][/tr]
[tr][td]26[/td][td]1[/td][td]0[/td][/tr]
[tr][td]27[/td][td]1[/td][td]1[/td][/tr]
[tr][td]28[/td][td]1[/td][td]0[/td][/tr]
[tr][td]37[/td][td]2[/td][td]1[/td][/tr]
[/table]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.