1

我有下表包含来自连锁店组的产品销售数据。数据又大又丑,但我只能从商店里得到它。有关信息,该表目前拥有 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 的产品。对于这些产品中的每一个,我需要显示条形码、描述、销售数量的总和、销售金额的总和,然后是产品所在的收款单数量,最后是所有产品的总和。

到目前为止,我已经设法提出以下建议。此查询在我的服务器上执行需要 2 分 20 秒,我认为“篮子总和”值不正确。我想知道是否有更好的方法在单个查询中,甚至在存储过程中执行此操作。

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

任何帮助,将不胜感激。谢谢。

4

1 回答 1

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]

这假设条形码没有两个[Desc],考虑到您要达到的结果,似乎就是这种情况。如果不是这种情况,可以将相同的查询更改为使用partition by Barcodeand distinct

对于您正在执行此操作的数据量,我认为您将希望您的聚集索引dtDatumstorecode.

于 2013-03-04T10:59:44.943 回答