从数据库中获取2周的数据

时间:2012-09-19 13:20:53

标签: sql sql-server-2008

我将返回最畅销产品列表。目前,我的查询带回了最近7天订单的总数。

我还需要带回前7天的项目数量之和,我想知道我会怎么做呢?我想它只是在@startDate上添加了7天,在@endDate上添加了13天(这已经在今天的日期之后设置了7天)

目前在 sum(amzOrdersItem.itemQty)AS订单行中获取商品数量。这基本上返回了产品订单的计数。

ALTER PROCEDURE [dbo].[GetHighestSellingItems]
@startDate datetime, 
@endDate datetime
AS
BEGIN

SET NOCOUNT ON;

SELECT    TOP (20) twProducts.sku, 
          twProducts.title + ' /  ' + LTRIM(CAST(twProducts.strength AS varchar(15))) + '%' AS Title, 
          sum(amzOrdersItem.itemQty) AS Orders, 
          twProducts.stock, aboProducts.asin, aboProducts.amzPrice
FROM      twProducts INNER JOIN
          amzOrdersItem ON twProducts.sku = amzOrdersItem.productSku INNER JOIN
          amzOrders ON amzOrdersItem.amzOrderId = amzOrders.amzOrderId INNER JOIN
          aboProducts ON twProducts.sku = aboProducts.sku
where    (amzOrders.orderDate between @startDate and @endDate) and  amzOrders.cancelled = 0
          group by twProducts.sku, twProducts.title, twProducts.strength, 
          twProducts.stock, aboProducts.asin, aboProducts.amzPrice
ORDER BY sum(amzOrdersItem.itemQty) DESC
END

认为这可能很方便,这是.net代码我填充到查询中,并获得结果。

public List<GetHighSelling> GetHighSellingWeek()
    {
        DateTime? endDate = DateTime.Now.Date;
        DateTime? startDate = DateTime.Now.Date.AddDays(-6).Date;

        using (aboDataDataContext dc = new aboDataDataContext())
        {
            var query = from o in dc.GetHighestSellingItems(startDate, endDate)
                        select new GetHighSelling
                        {
                            sku = o.sku,
                            title = o.Title,
                            itemQty = o.Orders,
                            stock = o.stock,
                            amzPrice = o.amzPrice.ToString(),
                            asin = o.asin
                        };
            return query.ToList();
        }
    }

2 个答案:

答案 0 :(得分:2)

将代码更改为

 DateTime startDate = DateTime.Now.Date.AddDays(-13).Date;

答案 1 :(得分:1)

你应该减去七天。如果你增加七天,你将要求在未来一周内销售最畅销的产品。

(虽然这将是非常有用的信息,但数据库无法看到未来。;)

您可以从结束日期开始计算开始日期:

DateTime? endDate = DateTime.Today.AddDays(-7);
DateTime? startDate = endDate.AddDays(-6);