日期:2014-05-18  浏览次数:20660 次

求一统计的sql语句
orders表有字段
goods(订单号),actiondate(订单时间),username(用户名)   ,state(订单状态)

users表
adddate(注册时间),username(用户名)

如何构造sql语句,得出一段时期内,比如2007-09-01到2007-09-07每天新增的客户数,每天新增客户的下单数,每天新增客户的当天state=0状态的下单数,新增客户中当天下单的客户数

------解决方案--------------------
---这样???????????
---每天新增的客户数,是不是要统计出每天的数量???
Select
Convert(Varchar(10),adddate,120) As 日期,
Count(username) As 新增的客户数
From
users
Where adddate> = '2007-09-01 ' And adddate <= '2007-09-07 '
Group By Convert(Varchar(10),adddate,120)

----每天新增客户的下单数???
Select
Convert(Varchar(10),actiondate,120) As 日期,
Count(1) As 新增客户的下单数
From
orders As A
Where actiondate> = '2007-09-01 ' And actiondate <= '2007-09-07 ' And
Exists(Select 1 From users Where username=A.username And
adddate> = '2007-09-01 ' And adddate <= '2007-09-07 ')
Group By Convert(Varchar(10),actiondate,120)

---每天新增客户的当天state=0状态的下单数????
Select
Convert(Varchar(10),actiondate,120) As 日期,
Count(1) As 新增客户的下单数
From
orders As A
Where actiondate> = '2007-09-01 ' And actiondate <= '2007-09-07 ' And state=0 And
Exists(Select 1 From users Where username=A.username And
adddate> = '2007-09-01 ' And adddate <= '2007-09-07 ')
Group By Convert(Varchar(10),actiondate,120)

----新增客户中当天下单的客户数????
Select
Convert(Varchar(10),adddate,120) As 日期,
Count(username) As 新增的客户数
From
users As A
Where adddate> = '2007-09-01 ' And adddate <= '2007-09-07 ' And Exists
(Select 1 From orders Where username=A.username And actiondate=A.adddate)
Group By Convert(Varchar(10),adddate,120)
------解决方案--------------------
--每天新增的客户数
Select Convert(Varchar(10),adddate,120) As 日期,Count(1) As 每天新增的客户数
From users Where adddate> = '2007-09-01 ' And adddate <= '2007-09-07 '
Group By Convert(Varchar(10),adddate,120)

----每天新增客户的下单数
Select Convert(Varchar(10),b.adddate,120) As 日期,Count(1) As 新增客户的下单数
From orders As A,users as B
Where a.username = b.username and Convert(Varchar(10),a.actiondate,120) = Convert(Varchar(10),b.adddate,120) and b.adddate> = '2007-09-01 ' And b.adddate <= '2007-09-07 ' Group By Convert(Varchar(10),b.adddate,120)

---每天新增客户的当天state=0状态的下单数
Select Convert(Varchar(10),b.adddate,120) As 日期,Count(1) As 新增客户的下单数
From orders As A,users as B
Where a.username = b.username and Convert(Varchar(10),a.actiondate,120) = Convert(Varchar(10),b.adddate,120) and a.state = 0 and b.adddate> = '2007-09-01 ' And b.adddate <= '2007-09-07 ' Group By Convert(Varchar(10),b.adddate,120)

----新增客户中当天下单的客户数
Select Convert(Varchar(10),adddate,120) As 日期,
Count(username) As 当天下单的客户数
From users As A
Where adddate> = '2007-09-01 ' And adddate <= '2007-09-07 ' And Exists
(Select 1 From orders Where username=A.username And actiondate=A.adddate)
Group By Convert(Varchar(10),adddate,120)

------解决方案--------------------
--假设各种数据在每天都有发生。如果没有,则使用left join
select t1.日期,t1.每天新增的客户数,
t2.每天新增客户的下单数,
t3.每天新增客户的当天state=0状态的下单数,
t4.新增客户中当天下单的人数
from
(
select convert(varchar(10),adddate,120) 日期,count(*) 每天新增的客户数
from users
where adddate > = '20