一、人人車:
1.設計一個銷售表,并給出SQL語句用來統計給定的時間段內,每人每天的銷售額和銷售總量。
create table sales {
?????????? id int not null auto_increment,
?????????? emp_id int not null,
?????????? sale_time int not null,? # 使用時間戳表示,為了索引查找方便
?????????? total dec(10,2),
????????? primary key(id),
????????? key(sale_time,emp_id)
}
--- 思路:
①每人每天的銷售額和銷售總量?
答:肯定得group by 每天,emp_id進行分組然后count(1),sum(total)就OK了
②核心在于每天怎么表示?
from_unixtime(sale_time,'%Y-%m-%d)
整體思路就是:先表示出每天每個人的記錄,作為結果集a ,然后在對結果集a分組獲得統計值
-- SQL語句:
假設開始時間戳為start,結束時間戳為end
select a.emp_id,a.time,count(1),sum(a.total) from ( select from_unixtime(sale_time,'%Y-%m-%d)? as time ,emp_id,total from sales where sale_time>=start and sale_time<=end ) as a group by a.time,emp_id oder by null;
-- 那么問題來了?
①每月/年 每人統計,怎么寫?
②如果sale_time字段定義為datetime類型該怎么寫?(提示:a.可以仿照上面寫;b.不使用子查詢而是直接在group by中使用year(sale_time),month(sale_time),day(sale_time),emp_id進行分組)
更多的時間函數參考:http://www.cnblogs.com/ggjucheng/p/3352280.html