我有下表,其中包含来自连锁店组的产品销售数据。数据既大又丑,但我能从商店获得它的唯一方法。 有关信息,该表目前拥有2200万条记录,每天增长约30万,这一增长率将按月呈指数增长约100%。
Store_Purchases(
[ID] [int] IDENTITY(1,1) NOT NULL,
[storecode] [int] NULL,
[dtDatum] [datetime] NULL,
[Barcode] [varchar](50) NULL,
[Desc] [varchar](100) NULL,
[qty] [int] NULL,
[amount] [money] NULL,
[TillslipID] [int] NULL)
根据日期范围内所有销售额的总和,我需要从中获取的查询是500强产品。对于这些产品中的每一种,我需要显示条形码,描述,销售数量的总和,销售金额的总和,以及产品所用的直至滑动的数量,最后是所有产品的总和。
到目前为止,我已设法提出以下内容。此查询需要2m20s才能在我的服务器上执行,我认为“Basket Sum”值不正确。我想知道在单个查询中,甚至在存储过程中是否有更好的方法。
SELECT
a.Barcode,
a.Desc,
SUM(b.amount) 'Basket SUM',
COUNT(distinct b.TillslipID) 'Basket Count',
Sales.Count,
Sales.Amount
FROM Store_Purchases b WITH (NOLOCK),
Store_Purchases a WITH (NOLOCK),
(
SELECT
top 500 Barcode,
sum(qty) "Count",
SUM(amount) "Amount"
FROM Store_Purchases WITH (NOLOCK)
WHERE (storecode = 30143)
AND dtDatum BETWEEN '1-Feb-2013 00:00:00' AND '28-Feb-2013 23:59:59'
GROUP BY Barcode
ORDER BY SUM(amount) DESC
) AS Sales
WHERE (a.storecode = 30143)
AND a.dtDatum BETWEEN '1-Feb-2013 00:00:00' AND '28-Feb-2013 23:59:59'
AND a.Barcode = Sales.Barcode
AND a.TillslipID = b.TillslipID
AND a.storecode = b.storecode
AND b.dtDatum BETWEEN '1-Feb-2013 00:00:00' AND '28-Feb-2013 23:59:59'
GROUP BY a.Barcode, a.Desc, Sales.Count, Sales.Amount
ORDER BYSales.Count DESC
任何帮助将不胜感激。感谢。
答案 0 :(得分:0)
select top 500 Barcode, [Desc], sum([Count]) as [Count], sum([Amount]) as Amount, sum(BasketSum) as [Basket Sum], count(TillslipID) as [Basket Count]
from (
select Barcode, [Desc], TillslipID, [Count], [Amount], sum(Amount) over (partition by TillSlipID) as BasketSum
from (
select TillslipID, Barcode, [Desc], sum(qty) as [Count], sum(amount) as [Amount]
FROM ez_Sparbuck_Products p
WHERE (storecode = 30143) and dtDatum between '1-Feb-2013 00:00:00' and '28-Feb-2013 23:59:59'
group by Barcode, [Desc], TillslipID,
) t
) t
group by Barcode, [Desc]
这假设条形码没有两个[s],考虑到你试图实现的结果,似乎就是这种情况。如果不是这种情况,则可以将此相同查询更改为使用partition by Barcode
和distinct
。
对于您正在执行此操作的数据量,我认为您需要dtDatum
上的聚集索引,并且可能需要storecode
上的某种分区。