本文共 921 字,大约阅读时间需要 3 分钟。
---1.平均销售等待时间
---有一张Sales表,其中有销售日期与顾客两列,现在要求使用一条SQL语句实现计算--每个顾客的两次购买之间的平均天数--假设:在同一个人在一天中不会购买两次create table sales(custname varchar(10) not null,saledate datetime not null)goinsert salesselect '张三','2010-1-1' unionselect '张三','2010-11-1' unionselect '张三','2011-1-1' unionselect '王五','2010-2-1' unionselect '王五','2010-4-1' unionselect '李四','2010-1-1' unionselect '李四','2010-5-1' unionselect '李四','2010-9-1' unionselect '李四','2011-1-1' unionselect '赵六','2010-1-1' unionselect '钱途','2010-1-1' unionselect '钱途','2011-3-1' unionselect '张三','2011-9-1' goselect custname,DATEDIFF(d,min(saledate),max(saledate))/(COUNT(*)-1) as avgdayfrom salesgroup by custnamehaving count(*)>1goselect custname,case when count(*)>1 then DATEDIFF(d,min(saledate),max(saledate))/(COUNT(*)-1)else DATEDIFF(d,min(saledate),max(saledate)) end as avgdayfrom salesgroup by custname--having count(*)>1godrop table sales转载地址:http://vhmkz.baihongyu.com/