2016-04-29 128 views
0

我有一个表:SQL Server:如何计算给定日期范围内的行数?

ID  StartDate  EndDate 

1  2016-01-01  2016-01-03 
2  2016-01-01  2016-01-01 
3  2016-01-01  2016-01-01 
4  2016-01-02  2016-01-02 

我想生成表示,对于一年中的每一天第二个表,行数,其中包括了开始和结束日期之间的时间内日历日期,是这样的:

WorkDate  NumActive 

2016-01-01  3 
2016-01-02  2 
2016-01-03  1 

目前我正尝试:

SELECT  COUNT(ID) 
FROM  TableOne 
WHERE  StartDate >= WorkDate 
     and EndDate  <= WorkDate 

这是给我零的一年中的每一天。

任何帮助表示赞赏 - 我是通过StackOverflow自学,我在这里有点过头了。

+2

你能提供的'创建两个原始表和* TableOne * table'报表? – trincot

+1

您的查询应该会生成一个错误,因为没有定义“WorkDate”。 –

+2

WHERE StartDate [更大或等于] WorkDate *和* EndDate [更小或等于] WorkDate。猜猜为什么它总是空的... – 2016-04-29 23:19:40

回答

0

这会给你结果。假设#cal作为TableOne

;with tal as (
select distinct number from master.dbo.spt_values 
where number between 1 and 365 
) 
, c2 as (
select DATEADD(d, number - 1, '2016-01-01') dt 
from tal 
) 
select dt AS WorkDate, COUNT(*) AS NumActive 
from c2 inner join #cal on c2.dt between #cal.StartDate and #cal.EndDate 
group by dt 
order by 1 

如果你想测试,使用下面的查询:

create table #cal (id int, StartDate date, EndDate date) 

insert into #cal values 
(1, '2016-01-01', '2016-01-03'), 
(2, '2016-01-01', '2016-01-01'), 
(3, '2016-01-01', '2016-01-01'), 
(4, '2016-01-02', '2016-01-02') 

结果

+-------------------------+-----------+ 
|  WorkDate   | NumActive | 
+-------------------------+-----------+ 
| 2016-01-01 00:00:00.000 |   3 | 
| 2016-01-02 00:00:00.000 |   2 | 
| 2016-01-03 00:00:00.000 |   1 | 
+-------------------------+-----------+ 

请 “标记为答案” 如果帖子已回答问题

0

您的where子句有错误的条件上。请看我的内嵌评论

CREATE TABLE #TempWorkDate (Id INT, StartDate DATETIME, EndDate DATETIME) 
GO 

INSERT INTO #TempWorkDate 
SELECT 1, DATEADD(D, +1, GETDATE()), DATEADD(D, +4, GETDATE()) UNION ALL 
SELECT 1, DATEADD(D, +1, GETDATE()), DATEADD(D, +1, GETDATE()) UNION ALL 
SELECT 1, DATEADD(D, +1, GETDATE()), DATEADD(D, +1, GETDATE()) UNION ALL 
SELECT 1, DATEADD(D, +2, GETDATE()), DATEADD(D, +2, GETDATE()) 
GO 

-- This query won't work, because the condition is wrong 
SELECT * FROM #TempWorkDate 
WHERE StartDate >= '2016-05-02' AND EndDate <= '2016-05-02' 

-- The below query returns the result 
SELECT * FROM #TempWorkDate 
WHERE StartDate <= '2016-05-02' AND EndDate >= '2016-05-02' 

DROP TABLE #TempWorkDate 
0

这会给你一个表中所有不同的StartDate的计数。 将其复制到EndDate中。 由于StartDate和EndDate可能不同,我不确定您的真实意图是计算日期范围吗?这是否意味着这个范围内的每一天都是+1?请澄清。

Select 
    StartDate 
    ,Count(*) over (partition by StartDate) as 'cntStartDates' 
From TableOne 
Group By StartDate 
0

试试这个,

declare @cal table (id int, StartDate date, EndDate date) 

insert into @cal values 
(1, '2016-01-01', '2016-01-03'), 
(2, '2016-01-01', '2016-01-01'), 
(3, '2016-01-01', '2016-01-01'), 
(4, '2016-01-02', '2016-01-02') 

;with t(id,dts) as (select id,startDate from @cal union all 
select t.id,dateadd(day,1,dts) from t join @cal t1 on t.id=t1.id where t.dts<t1.EndDate) 

select dts WorkDate,count(dts) NumActive from t group by dts