现在有几千万数据,分别是用户,购买的物品,购买时间,及数量。现在要算出每个客户每次购买的时候,该物品累计到本次购买一共是多少件。用户有几万,物品有400多种。目前用cte,1500条记录就跑了半个小时还没有出来。

解决方案 »

  1.   

    可否把你写的WITH语句贴出来,看看能不能优化下
      

  2.   


    with t(timestr,itemid,[user],amountt)
    as(
    select [time],itemid,[user],min(cast(amount as int)) from itemusetmp   group by [time],itemid,[user]
    union all
    select p.[time] ,p.itemid,p.[user],convert(int,p.amount+e.amountt)  from itemusetmp p , t e 
    where p.[itemid]=e.itemid and p.[user]=e.[user] and p.[time]>e.[timestr]
     )
      

  3.   

    with t(timestr,itemid,[user],amountt)
    as(
    select [time],itemid,[user],min(cast(amount as int)) from itemusetmp   group by [time],itemid,[user]
    union all
    select p.[time] ,p.itemid,p.[user],convert(int,p.amount+e.amountt)  from itemusetmp p , t e 
    where p.[itemid]=e.itemid and p.[user]=e.[user] and p.[time]>e.[timestr]
     )
      

  4.   

    大数据量的递归用with语句不太合适,试试改成其他方式
      

  5.   

    select a.[time],a.itemid,a.[user],b.[amount] from itemusetmp a,
    (select max([time]) 'time',sum(amount) 'amount',itemid,[user] from itemusetmp group by itemid,[user]) b
    where a.itemid=b.itemid and a.[user]=b.[user]
      

  6.   

    兄弟,这个语句不行,只能求出最大的,而不是求每次购买后,使用完道具的时间。
    道具 购买数量  购买时间
    A     10        1
    A      3        12
    道具 使用数量 使用时间
    A      1       2
    A      1       3
    A      1       4
    A      1       5
    A      1       6
    A      1       7
    A      1       8
    A      1       9
    A      1       10
    A      1       11
    A      1       13
    A      1       14
    A      1       15
    想要的结果是
    道具  购买数量 购买时间 使用完时的时间
    A      10       1        11
    A      10       12        15
      

  7.   

    你的 amount 不是int 类型的?看了下语句没啥优化的余地[time],itemid,[user] 这散列上弄一个组合索引试试
      

  8.   

    amout是int型,我加上索引试试吧,要是再不行,可就郁闷死了
      

  9.   

    大数据量就别用CTE了,我记得临时表好像是可以实现的,不过没线程代码。我对80万数据用CTE还不错,但是比较危险,因为那个嵌套次数只能到32676。千万级容易爆掉,但是切记,不要用游标和while。
      

  10.   


    好像不用cte 去递归吧你试试下面这个语句
    select a.[time],a.itemid,a.[user],b.[amount],
    amount=(
    select sum(amount) from itemusetmp b WHERE a.itemid=b.itemid and a.[user]=b.[user] AND b.[time]<=a.[time]

    from itemusetmp a
      

  11.   

    试试这个:
    with t as
    (select *,ROW_NUMBER() over(partition by  [user],[itemid]  order by [time]) as rn from [itemusetmp])
    select a.rn,a.[time],a.[user],a.[itemid],a.[amount],a.[amount]+isnull(SUM(b.amount),0) as amountt From t a left join t b
    on a.[user]=b.[user] and a.itemid=b.itemid and a.rn>b.rn 
    group by a.rn,a.[time],a.[user],a.[itemid],a.[amount]
    order by a.[user],a.[itemid],a.[time]