现有投资表和业务员表,表结构如下:
示例数据如下:
1. 计算2017年每一笔投资均大于50万的用户
#每一笔投资额都大于50万,对应最小投资额大于50万即可
select user_id
from invest
where year(created_at) = 2017 # where created_at like "2017/%" 模糊匹配
group by user_id
having min(investamount)>500000
首先选择2017年的数据,按照用户ID进行分组,最后筛选最小投资额大于50万的用户即可
2. 计算2017年仅投资过CFH和AX产品的用户
select user_id
from invest
where created_at like "2017/%"
group by user_id
having sum(invest_item="CFH") and sum(invest_item="AX") and count(distinct invest_item)=2
要求投资过CFH和AX,同时要求没有投资过其他产品,所有需要再加上一个限定:count(distinct invest_item)=2
3. 计算归属于10002业务员的投资金额
# 需要连接投资表和业务员表,如果通过用户id进行匹配,则是多对多的结果,出现混乱
# 并且用户在不同时间会更换业务员,需要同时注意user_id 和业务时间
select agent_id, sum(investamount) as "投资金额"
from invest
join agent on invest.user_id = agent.user_id
and invest.created_at between agent.start_date and agent.end_date
where agent.agent_id = "10002";