您的位置:首页 > 数据库 > MySQL

mysql查询

2015-09-10 14:50 549 查看
数据表customers(customerid,name,address,city)

数据表orders(orderid,customerid,amount,date)

Q:查询所有最后交易日期在9月的顾客的7月、8月的订单利润(单笔订单价格大于等于50利润为该单价格的50%,小于50则利润为1),要求显示顾客的name及从中的获利总额

分析问题,首先是最后交易日期在9月

1.查询出所有顾客的最后交易日期

select customerid,max(date) from orders group by customerid


2.筛选出最后交易日期在9月的顾客信息
select customerid,date from orders where date in (select max(date) from orders group by customerid) && date_format(date,'%m-%y')='09-15'


3.查询顾客的7、8月的交易记录

select orderid,customerid,date from orders where date_format(date,'%m-%y')>'06-15' and date_format(date,'%m-%y')<'09-15' order by customerid


4.最后交易日期在9月的顾客的7、8月的订单

select * from orders where customerid
in (select customerid from orders where date in
(select max(date) from orders group by customerid) && date_format(date,'%m-%y')='09-15') && date_format(date,'%m-%y')>'06-15'
and date_format(date,'%m-%y')<'09-15' order by customerid


5.核算获利,单笔订单金额大于等于50则获利为50%,否则为1
select orderid,customerid,sum(case when amount>=50 then amount/2 else 1 end) as huoli from orders group by customerid


所有条件已查询出,合并sql

select c.name,o.customerid,sum(case when o.amount>=50 then o.amount/2 else 1 end) as huoli from orders as o ,customers as c where o.orderid
in( select orderid from orders where customerid
in (select customerid from orders where date in
(select max(date) from orders group by customerid) && date_format(date,'%m-%y')='09-15') && date_format(date,'%m-%y')>'06-15'
and date_format(date,'%m-%y')<'09-15' order by customerid)  && c.customerid=o.customerid group by o.customerid
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: