查询从年初开始的每周的总计

时间:2015-08-23 00:30:49

标签: sql sql-server sql-server-2008 sql-server-2012

嗨,我有一张如下表:

Item    Date    Quantity
1   1/1/2015    34
1   1/1/2015    34
1   1/2/2015    23
1   7/1/2015    12
1   6/25/2015   4
1   1/1/2015    1
2   1/1/2015    53
2   1/2/2015    42
2   7/1/2015    12
2   6/25/2015   66

我想运行一个查询,以查看从年初开始的每周项目的数量。我有办法吗?

Output :
Item WeekendDate Quantity 
1         01/03/2015   92

这是我走了多远,我不知道如何继续前进:

select Item, Date, Sum(Quantity) from Table T 
group by Item, Date

2 个答案:

答案 0 :(得分:2)

测试数据

#comment88

查询

DECLARE @TABLE TABLE (Item INT, [Date] DATE, Quantity INT)
INSERT INTO @TABLE VALUES
(1   ,'1/1/2015',    34),
(1   ,'1/1/2015',    34),
(1   ,'1/2/2015',    23),
(1   ,'7/1/2015',    12),
(1   ,'6/25/2015',   4),
(1   ,'1/1/2015',    1),
(2   ,'1/1/2015',    53),
(2   ,'1/2/2015',    42),
(2   ,'7/1/2015',    12),
(2   ,'6/25/2015',   66)

结果

SELECT Item
     ,DATEADD(DAY, 7 - DATEPART(WEEKDAY, [Date]), CAST([Date] AS DATE)) Weekend
     ,SUM(Quantity) Week_Total
FROM @TABLE
GROUP BY Item, DATEADD(DAY, 7 - DATEPART(WEEKDAY, [Date]), CAST([Date] AS DATE))

答案 1 :(得分:0)

这是另一个将日期“截断/舍入”为一周精度的变体。

DECLARE @TABLE TABLE (Item INT, dt DATE, Quantity INT)
INSERT INTO @TABLE VALUES
(1   ,'2015-01-01',    34),
(1   ,'2015-01-01',    34),
(1   ,'2015-01-02',    23),
(1   ,'2015-07-01',    12),
(1   ,'2015-06-25',     4),
(1   ,'2015-01-01',     1),
(2   ,'2015-01-01',    53),
(2   ,'2015-01-02',    42),
(2   ,'2015-07-01',    12),
(2   ,'2015-06-25',    66);

SELECT
    Item
    ,DATEADD(week, DATEDIFF(week, '20150103', dt), '20150103') AS Weekend
    ,SUM(Quantity) Week_Total
FROM @TABLE
GROUP BY
    Item
    ,DATEADD(week, DATEDIFF(week, '20150103', dt), '20150103')

<强>结果

Item     Weekend                    Week_Total
1        2015-01-03 00:00:00.000    92
2        2015-01-03 00:00:00.000    95
1        2015-06-27 00:00:00.000    4
2        2015-06-27 00:00:00.000    66
1        2015-07-04 00:00:00.000    12
2        2015-07-04 00:00:00.000    12

在这种方法中,选择一周的开始/结束日期可能更容易。只需在公式中添加另一个日期而不是20150103。在一些国家,周从星期一开始,而不是星期日。此外,此方法不依赖于影响DATEPART函数结果的服务器设置。

  

当datepart是星期(wk,ww)或工作日(dw)时,返回值   取决于使用SET DATEFIRST设置的值。