我有下表包含来自连锁店组的产品销售数据。数据又大又丑,但我只能从商店里得到它。有关信息,该表目前拥有 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
任何帮助,将不胜感激。谢谢。