我有一个表格,显示几天内在空间网格中发生的事件,我想为网格的每个单元格选择唯一天数,以便获取事件发生的天数,这里我的表结构:
+-----+------------+------------+---------+---------+
| id | start_date | end_date | id_cell | event |
+-----+------------+------------+---------+---------+
| 1 | 2017-03-01 | 2017-03-04 | 250 | envent1 |
| 2 | 2017-03-01 | 2017-03-04 | 251 | envent1 |
| 3 | 2017-03-01 | 2017-03-04 | 307 | envent1 |
| 4 | 2017-03-01 | 2017-03-04 | 308 | envent1 |
| 5 | 2017-03-01 | 2017-03-09 | 250 | event2 |
| 9 | 2017-02-24 | 2017-03-03 | 250 | event3 |
| 13 | 2017-02-24 | 2017-03-24 | 250 | event4 |
| 17 | 2017-02-24 | 2017-03-02 | 250 | event5 |
| 21 | 2017-01-04 | 2017-01-25 | 250 | event6 |
| 25 | 2017-03-26 | 2017-03-28 | 250 | event2 |
+-----+------------+------------+---------+---------+
例如,250为id的单元格的预期结果为51天:
2017-01-04 -> 2017-01-25 = 21 days
2017-02-24 -> 2017-03-24 = 28 days
2017-03-26 -> 2017-03-28 = 2 days
其他日期都包含在2017-02-24和2017-03-24之间,因此不必计算在内,所以21 + 28 + 2 = 51天。
我试图像这样使用DATEDIFF():
select datediff(max(end_date) , min(start_date) ) from cell_date where id_cell = 250
结果为83,因为它计算2017-01-25和2017-03-01之间的天数,即未发生事件的日期。
我尝试了DATEDIFF的一些请求,但我无法弄清楚如何做到这一点。有人可以帮帮我吗?提前谢谢。
答案 0 :(得分:1)
您可以通过按cell_id分组并计算各个差异的总和来实现此目的:
Select cell_id,[other columns],Sum(datediff(days,start_date,end_date)) as Days
From my_table
group by cell_id,[other columns]
修改强>
根据您的需要,我认为您应该使用中间表存储个人日期(确定它不是最佳方式),将它们与您的活动结合,然后选择结果中的不同日期。这是实现它的代码
/*Your example Talbe*/
DECLARE @T
TABLE(ID INT,startDate DATE,EndDate DATE,id_cell INT,evnt NVARCHAR(20) )
INSERT INTO @T
VALUES
(1,'2017-03-01','2017-03-04',250,'event1'),
(2,'2017-03-01','2017-03-04',251,'event1'),
(3,'2017-03-01','2017-03-04',307,'event1'),
(4,'2017-03-01','2017-03-04',308,'event1'),
(5,'2017-03-01','2017-03-09',250,'event2'),
(9,'2017-02-24','2017-03-03',250,'event3'),
(13,'2017-02-24','2017-03-24',250,'event4'),
(17,'2017-02-24','2017-03-02',250,'event5'),
(21,'2017-01-04','2017-01-25',250,'event6'),
(25,'2017-03-26','2017-03-28',250,'event2')
/*Table to store days: ideally get the start and end dates from your table */
DECLARE @STARTDATE DATE='2017-01-04'
DECLARE @ENDDATE DATE='2017-03-28'
DECLARE @DAYS
TABLE(oneday DATE)
WHILE @StartDate <= @endDate
BEGIN
INSERT INTO @days
(
oneday
)
SELECT
@StartDate
SET @StartDate = DATEADD(dd, 1, @StartDate)
END
/*The request */
SELECT id_cell,COUNT(DISTINCT oneday) NUMBER_OF_DAYS
FROM @T t
JOIN @DAYS d ON d.oneday>=t.startDate AND d.oneday<t.EndDate
WHERE id_cell=250
GROUP BY id_cell
答案 1 :(得分:0)
您可以使用max和min date和datediff来获取日期之间的差异,例如:for event
select event, datediff(max(end_date) , min(star_date) )
from my_table
group by event
或yuo可以通过cell_id求和cell_id的总和
select cell_id, sum(datediff(end_date , star_date) )as days
from my_table
group by cell_id
或 对于您的样本,您似乎需要max end_date来查找从同一天开始的某些事件
select id_cell, sum(datediff(max_end_date, start_date)) as days
from (
select id_cell, start_date, max(end_date) as max_end_date
from cell_date
group by id_cell, start_date ) t
group by id_cell