如何从表中总结选定的日期

时间:2014-05-05 08:27:55

标签: sql sql-server

考虑以下查询,该查询生成他们购买特定产品的customerid和天数,显然每个客户将拥有他/她购买商品的不同日期。我想要做的是在客户购买该产品的那些日子里完成购买。

我有ff查询。

Select customerid, eventdate
into #days
from table1
where product='chocolate'

现在我想总结所有在客户购买巧克力的日子里购买的商品。 所以我有

select customerid, sum(purchases) purchases
into #pur
from table1 a
where eventdate in (select eventdate from #days where customerid=a.customerid)
group by customerid

但是上面的时间很长,所以我取消了它。 请帮助更好的查询。

4 个答案:

答案 0 :(得分:0)

这为每位购买巧克力的客户 AND 提供了购买总额。

select customerid, eventdate ,sum(purchases) purchases
into #pur
from table1
where product='chocolate'
group by customerid,eventdate 

如果你想在巧克力被带来时完全购买,那么就这样做

select customerid,sum(purchases) purchases
into #pur
from table1
where product='chocolate'
group by customerid

根据您的澄清

select customerid, sum(purchases) purchases
into #pur
from table1 a
where eventdate in (select eventdate from table1 where product='chocolate')
group by customerid

我建议您在eventdate列上应用索引以提高查询性能。

答案 1 :(得分:0)

客户购买的所有商品的总和,仅计算他购买巧克力的日期。

SELECT customerid, sum(purchases) purchases
FROM table1 a
WHERE eventdate IN
  (SELECT eventdate
   FROM table1
   WHERE product = 'chocolate'
   AND customerid = a.customerid)
GROUP BY customerid;

答案 2 :(得分:0)

不确定这是否可行但是尝试一下。如果没有,那么请您提供样本数据和预期输出,以便我们能够以更好的方式进行尝试

select customerid, sum(purchases) purchases
into #pur
from table1 a
inner join #days d 
ON d.customerid = a.customerid
AND d.eventdate = a.eventdate
group by customerid

或尝试此查询

select customerid, sum(purchases) purchases
into #pur
from table1 a
inner join #days d 
ON d.customerid = a.customerid
WHERE d.eventdate = a.eventdate
group by customerid

希望这有帮助

答案 3 :(得分:0)

经过仔细思考后,以下工作对我有用,而且速度更快。

- 删除表#days 选择customerid,eventdate 进入#days 来自table1 with(nolock,index(ix_eventdate)) 在20140401和20140430之间的事件日期 和产品='巧克力'

- 删除表#pur 选择customerid,eventdate,购买
进入#pur 来自table1 with(nolock,index(ix_eventdate)) 其中eventdate介于20140401和20140430之间

- 删除表#first 选择a。*,b。购买 从#days到#first a 左连接#pur b 在a.customerid = b.customerid上 和a.EventDate = b.EventDate

- 从#first

中选择*

- 删除表#purdays 从#first中选择customerid,将(购买)收入计入#purdays 由customerid分组 按customerid订购

从#purdays

中选择*