SQL TSQL查询每周获取设备数

时间:2016-02-29 12:59:30

标签: sql tsql count sql-server-2008-r2 helpers

ID | Equipment   |  HireDate    |  HireTodate   | ActualOffhireDate
---------------------------------------------------------------------
01 | Printer     |  01/01/2013  |   31/12/2016  |
02 | Printer     |  01/05/2015  |   31/12/2016  |
03 | Laptop      |  17/01/2016  |   31/12/2016  |
04 | Laptop      |  01/01/2015  |   31/12/2016  |  28/01/2016

我喜欢上表,并希望根据下面的每周(从周五到周六)计算2016年1月份的点数

Equipment |  January count  | Week 1| Week 2| Week 3| Week 4
------------------------------------------------------------------
Printer   |   02            |  02   |  02   |  02   |  02
Laptop    |   02            |  01   |  01   |  02   |  01

1 个答案:

答案 0 :(得分:0)

您需要有一个日历表,可以非常快速且轻松地处理此类查询。

这是我用来生成calendar表的一种方式......在我的环境中它看起来像下面......

enter image description here

一旦你有了日历表,你所要做的就是加入想要计算的日期,这就像下面这么简单

select 
equipment,
count(*) as 'Jancount',
sum(case when wkno =1 then 1 else 0 end) 'Week 1',
sum(case when wkno =2 then 1 else 0 end) 'Week 2',
sum(case when wkno =3 then 1 else 0 end) 'Week 3',
sum(case when wkno =4 then 1 else 0 end) 'Week 4'
from
calendar c
join testtable p
on p.hiretodate=c.date
group by equipment

<强>输出:
enter image description here