SQL - 比较表

时间:2016-03-29 13:35:20

标签: sql ms-access

如何使用SQL从原始表中获取修订后的表?基本上,我想要做的是根据日期比较客户数据的行。在一个月内的15天内购买任何商品的顾客将被视为购买1件商品。例如,对于顾客Paolo Arcotti,虽然他在15天内进行了3次购买,但只考虑第一次购买并计为1次购买;而对于客户Hanna Moss来说,这被认为是2次购买。简而言之,我想将1月1日至15日的购买分类为1次购买,将16-30次购买归类为另一次购买。

Original Table vs Revised Table

2 个答案:

答案 0 :(得分:0)

数据库支持日期功能,但每个数据库都不同。以下方法使用not exists和函数来表示日期的日期,月份和年份:

select t.*
from original as t
where not exists (select 1
                  from original as t2
                  where t2.customer = t.customer and
                        datepart("yyyy", t2.date) = datepart("yyyy", t.date) and
                        datepart("m", t2.date) = datepart("m", t.date) and
                        t2.date < t.date and
                        ((datepart("d", t2.date) <= 15 and datepart("d", t.date) <= 15) or
                         (datepart("d", t2.date) > 15 and datepart("d", t.date) > 15)
                        )
                 );

答案 1 :(得分:0)

;with cte as 
(
select *,DATEPART(d,orderdate) as dayofmonth1,row_number() over(partition by customer order by customer,orderdate ) as rn from #test 
where DATEPART(d,orderdate)<=15
)
, cte1 as
(
select *,DATEPART(d,orderdate) as dayofmonth1,row_number() over(partition by customer order by customer,orderdate )as rn from #test 
where DATEPART(d,orderdate)>15
)
select *from cte where rn=1
union select *from cte1 where rn=1