简体   繁体   中英

select sql query from two tables

You have two tables “members” and “policies”. If you are asked to prepare a report for the number of members between age groups of 12-20, 21-30, 31-40 and over 41 who have bought insurance during the month of December 2014.

Assume all the fields you need are in the tables; How can I prepare the SQL statement(s) to accomplish this task. The table fields are shown below (not necessarily the correct name)

The members table has these fields birthday (DATE), firstname, surname The policies table has these fields policy_start_date (DATE), policy_amount (DECIMAL), policy_claim_status (TINYINT), policy_description (VARCHAR 160)

Can you clarify whether you mean 'prepare' as in prepared statement or are you asking what the syntax would be?

You may want to break the problem down into a number of sub-queries like

  • Top level report which joins the queries below.
  • Extract details of the member like their date of birth to a age bucket.
  • Filter policies created in your time period.

This will give you a start

select 
sum(case when datediff(current_date(),birthDate)/365 between 12 and 20 then 1 else 0 end) as `age_12to20`,
sum(case when datediff(current_date(),birthDate)/365 between 21 and 30 then 1 else 0 end) as `age_21to30`,
sum(case when datediff(current_date(),birthDate)/365 between 31 and 40 then 1 else 0 end) as `age_31to40`,
sum(case when datediff(current_date(),birthDate)/365 >40 then 1 else 0 end) as `age_over40`
from members as m inner join policies as p
on m.member_id=p.member_id
where policy_start_date>='2014-12-01' and policy_start_date<'2015-01-01'

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