如何在SQL Server中将包含weekstart日期和结束日期的每周报告作为列名称

时间:2015-09-19 07:09:07

标签: sql-server

数据:

Date        Productivity
-------------------------
01/06/2015      50
01/06/2015      50
02/06/2015      60
02/06/2015      50
01/06/2015      55
03/06/2015      50
03/06/2015      50
03/06/2015      50
04/06/2015      50
04/06/2015      50
04/06/2015      50
05/06/2015      50
05/06/2015      50
05/06/2015      50
06/06/2015      50
06/06/2015      50
08/06/2015      50
08/06/2015      50
09/06/2015      50
10/06/2015      50
11/06/2015      50
12/06/2015      50
13/06/2015      50
13/06/2015      50
13/06/2015      50

我想要这样的输出,其中包含平均每周生产力:

Date                         Productivity
------------------------------------------
01/06/2015-06/06/2015           50.93
08/06/2015-13/06/2015            50

2 个答案:

答案 0 :(得分:2)

<强> SqlFiddle

SELECT 
  [date]          = CONVERT(NVARCHAR(100), MIN([date]), 103 ) + '-' +
                    CONVERT(NVARCHAR(100), MAX([date]), 103 )
  ,[Productivity] = CAST(AVG(Productivity * 1.0) AS DECIMAL(10,2))
FROM tab
GROUP BY DATEPART(wk, [Date]);

修改

如果数据不包含所有日期,则添加计算周开始和结束。

<强> SqlFiddleDemo2

set datefirst 1;

SELECT 
   [date]          = CONVERT(NVARCHAR(100), DATEADD(dd, -(DATEPART(dw, MIN([date]))-1), MIN([date])), 103 ) + ' - ' +  CONVERT(NVARCHAR(100), DATEADD(dd, 7-(DATEPART(dw, MAX([date]))), MAX([date])), 103 )
   ,[Productivity] = CAST(AVG(Productivity * 1.0) AS DECIMAL(10,2))
FROM tab
GROUP BY DATEPART(wk, [Date]);

答案 1 :(得分:0)

Lad的答案将满足您的需求。但是,如果需要几个星期没有进入Avg&#39; 0&#39;你可能不得不写一篇cte来找出那些应该与小伙伴一起回答的周?