日期:2014-05-19  浏览次数:20440 次

请教sql统计
CustomerDB(CustomerID,customerName,AddDate)
OrderDB(OrderId,CustomerId,AddDate)
OrderDetailDB(OrderDetailId,OrderId,Amount,Price)

订单记录、顾客记录(2005年到至今)
1   统计   2007/01-2007/07,每个月订单中新客户数(不含重复顾客下单)
    比如:1月份订单中新顾客数量(也就是在   2007/01之前没下过订单的顾客数量)

2   统计   2007/01-2007/07,每天订单中新客户(不含重复顾客下单)
    比如:2007/01/01   订单中新顾客数量(也就是在   2007/01/01之前没下过订单的顾客数量)

    按按月查询,但按天统计的结果,如下   2007-01-01—2007-01-31统计结果如下:
    Date           Amount    
2007-01-01       10
2007-01-02       20
2007-01-02         0
...
2007-01-31       20


------解决方案--------------------
sql语句未测试不知道是不是你想要的!

1.
select 总订单数=count(distinct CustomerId)
from OrderDB
where year(AddDate)=2007 and month(AddDate) between 1 and 7

2.
select 总订单数=count(distinct CustomerId)
from OrderDB
where year(AddDate)=2007 and month(AddDate) between 1 and 7
group by 日期 asc


------解决方案--------------------
1.
select Convert(char(7),b.AddDate,120) as AddMonth,
Count(Distinct CustomerId) as NewCustomCount
from OrderDetailDB a
inner join OrderDB b on a.OrderId=b.OrderId
where AddDate between '2007-1-1 ' and '2007-7-31 '
and b.CustomerId not in
(select CustomerId from OrderDB where Convert(char(7),AddDate,120) <Convert(char(7),b.AddDate,120)
group by Convert(char(7),b.AddDate,120)

2.
select b.AddDate,
Count(Distinct CustomerId) as NewCustomCount
from OrderDetailDB a
inner join OrderDB b on a.OrderId=b.OrderId
where AddDate between '2007-1-1 ' and '2007-1-31 '
and b.CustomerId not in
(select CustomerId from OrderDB where AddDate <b.AddDate)
group by b.AddDate