1

我有一个表名“订单”。

我想按当月的周数计算总订单量。

目前,我可以使用以下查询按月获得总订单:-

SELECT 
                    "Month" = month(o.OrderDate)
                     , "Year" = year(o.OrderDate)
                     , Amount = sum(o.Total)
                FROM
                    Orders o
                WHERE
                    o.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
                    AND o.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
                GROUP BY
                    month(o.OrderDate)
                  , year(o.OrderDate)
                ORDER BY
                    year(o.OrderDate)
                  , month(o.OrderDate)

但现在我想像下面这样按周获得这些数据:-

因为我们每年大约有 52 周,所以数据应该是这样的:-

周 年 金额 1 2013 200 2 2013 500 ....... 52 2013 0

提前致谢。

4

3 回答 3

3

您可以使用DATEPART获取周数。

要获取每周的行,即使该周没有注册,您也可以使用数字表并左连接到您的订单表。

此查询将为您提供2013恰好有53几周的年份。

select N.Number as [Week],
       2013 as [Year],
       sum(O.Total) as Amount
from dbo.Numbers as N
  left outer join dbo.Orders as O    
    on n.Number = datepart(week, O.OrderDate) and
       O.OrderDate >= '20130101' and
       O.OrderDate < '20140101'
where n.Number between 1 and 53
group by N.Number
order by N.Number;

如果您没有或想要创建一个数字表,您可以使用它来代替,它将在查询中为您创建一个。

select N.Number as [Week],
       2013 as [Year],
       sum(O.Total) as Amount
from (
     select top (53) row_number() over(order by 1/0) as Number
     from sys.all_objects
     ) as N
  left outer join dbo.Orders as O    
    on n.Number = datepart(week, O.OrderDate) and
       O.OrderDate >= '20130101' and
       O.OrderDate < '20140101'
where n.Number between 1 and 53
group by N.Number
order by N.Number;
于 2013-10-24T05:53:24.800 回答
2

请尝试如下

           SELECT 
                 DATEPART (wk, o.OrderDate)as week,                    
                 year(o.OrderDate) as year
                 , Amount = sum(o.Total)
            FROM
                Orders o
            WHERE
                o.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
                AND o.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
            GROUP BY
                DATEPART(wk, o.OrderDate)
              , year(o.OrderDate)
            ORDER BY
                year(o.OrderDate)
              , DATEPART(wk, o.OrderDate)
于 2013-10-24T05:55:10.140 回答
0

请试试这个
,你可以取一个数值为 1...53 的数字表,然后用这个表左外连接,如果你没有数据,它将导致 0 周。

       select numbers.value,numbers.[Year],amt from numbers left outer join (
        SELECT 
             DATEPART (wk, o.OrderDate)as week,                    
             2013 as [Year],
             ,sum(o.Total)as amt
        FROM
            Orders o
        WHERE
            o.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
            AND o.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
        GROUP BY
            DATEPART(wk, o.OrderDate)
          , year(o.OrderDate)
        ORDER BY
            year(o.OrderDate)
          , DATEPART(wk, o.OrderDate)
      )data on data.week=numbers.value
于 2013-10-24T06:44:50.887 回答